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?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With