Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying number of decimal places for individual fields in pandas to csv

I am using pandas to_csv function, and want to specify the number of decimal places for float numbers. However, I want this to change based on the field.

For example:

my data set looks like this:

sampleID     Call     X      Y 
1234         0.1234   0.123  0.123

I want the Call column to always have 4 decimal places and X and Y to always have 3.

Originally, I would use the float_format argument in to_csv, but that only appears applicable if all floats are treated the same way. How would I go about specifying the number of digits for individual columns?

like image 224
Carrie Brown Avatar asked Mar 11 '23 15:03

Carrie Brown


1 Answers

You can round the columns before saving as a CSV. If you need the precision you can copy the DataFrame to retain precision in the original DataFrame.

df['X'] = df['X'].round(3)
df['Y'] = df['Y'].round(3)
df.to_csv('file.csv')
like image 50
Waylon Walker Avatar answered Apr 26 '23 02:04

Waylon Walker