Hatshepsut
Hatshepsut

Reputation: 6652

Write csv with all numeric columns as float with 3 decimal points

I have several columns of different types. I would like to format all the numeric columns into a csv as .3 floats. So in this case, a and b should become 1.000 and 2.000 but c should stay 3 because its value is a string, not a number.

import io 
sio = io.StringIO() 
(pd.DataFrame([{'a': 1, 'b': 2.0, 'c': '3'}])
 .astype(float)
 .to_csv(sio, index=False, float_format='{:.2f}'))



TypeError: not all arguments converted during string formatting

Upvotes: 0

Views: 236

Answers (1)

SamProell
SamProell

Reputation: 381

First of all, when you use astype(float), the third column is converted to float, if it is a valid number. Otherwise, astype will raise an exception. So you should probably change the types for each column separately. Second, the error is caused by an invalid format specifier. It should be "%.2f".

import io
sio = io.StringIO()
df = pd.DataFrame([{'a': 1, 'b': 2.0, 'c': '1'}])
df[['a', 'b']] = df[['a', 'b']].astype(float)
df.to_csv(sio, index=False, float_format='%.3f')

Upvotes: 2

Related Questions