Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing pandas dataframe to CSV with decimal places [duplicate]

Tags:

python

pandas

csv

Background - I am trying to round the values of 2x columns (Entity ID % and Account # %) to 7 decimal places in a pandas Dataframe, before writing to a .csv

Function - this function takes a dataframe (df) strips out any rows that don't meet a criteria and write the df to a .csv. Importantly, I have a line of code that reads df.round({'Entity ID %': 7, 'Account # %': 7}) which I thought 'should' be rounding all the values in those columns to 7 decimal places.

def ownership_exceptions():
    df = ownership_qc()
    df.round({'Entity ID %': 7, 'Account # %': 7})
    df = df[(df['Entity ID %'] != 1.000000) & (df['Account # %'] != 1.000000)]
    #   Counting rows in df
    index = df.index
    number_of_rows = len(index)
    timestr = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M")
    filename = 'ownership_exceptions_'+timestr
    with open(filename, 'w') as output_data:
        df.to_csv(filename+'.csv')
    print("---------------------------\n","EXCEPTION REPORT:", number_of_rows, "rows", "\n---------------------------")
    return df

Expected output (per a preview of df -

enter image description here

Actual .csv output -

enter image description here

Question - Should be de defining the decimal places as part of the df.to_csv? What am I missing which is causing this erroneous output of 17 decimal places?

like image 494
William Avatar asked Dec 05 '25 09:12

William


1 Answers

Your problem is probably because you don't set the output of round to df:

# Replace
df.round({'Entity ID %': 7, 'Account # %': 7})

# By
df = df.round({'Entity ID %': 7, 'Account # %': 7})
like image 187
Corralien Avatar answered Dec 06 '25 23:12

Corralien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!