I`m trying to write to a csv a pandas DataFrame with a column with various data types. I need all the float values to have exactly 4 decimal places.
For example. I define a new df:
df=pd.DataFrame({'col1': [0.24567899874, 'a'], 'col2' : [0.123456789, 1] })
And then writting it to a csv file using float_format:
df.to_csv('example.csv', float_format='%.4f')
I get the result: col1, col2 0.24999999999986597,0.1234 a,1.0000
It seems that float_format only applies to columns in which all their elements are numeric values.
for col in df.columns:
if df[col].dtype == 'float':
df[col].round(4)
You could do this:
for col in df.columns:
df[col] = df[col].apply(lambda x: '{:.4f}'.format(x) if type(x) is int or type(x) is float else x)
df.to_csv('example.csv')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.