I'm trying to export a CSV string to a D3 web application, but the command to_csv
insists on adding a trailing 0 to the data, which prevents a proper use by D3.
Here's a minimal example to illustrate the problem.
My (simplified) dataframe is:
>>> df = pd.DataFrame([['Alex',20.0000, 50.650]],columns=['Name','Age', 'Weight'])
Name Age Weight
0 Alex 20.0 50.65
df['Age']
contains a float
, as indicated by:
>>> df['Age']
0 20.0
Name: Age, dtype: float64
Then based on this answer I run .astype(object)
to get the format I would like:
>>> df=df.astype(object)
Name Age Weight
0 Alex 20 50.65
Now, df['Age']
contains an object
, with no trailing zero:
>>> df['Age']
0 20
Name: Age, dtype: object
That's what I would like to export with to_csv
, but this command reappends a trailing 0 to the number, which I want to avoid:
>>> df_csv = df.to_csv(sep=',', index = False)
>>> df_csv
'Name,Age,Weight\nAlex,20.0,50.65\n'
I tried using df_csv = df.to_csv(sep=',', index = False, float_format='%.0f')
based on this answer, but that doesn't work because there are other floats in my dataframe for which I wish to keep non-zero decimals.
How could I prevent this trailing 0 to appear for numbers with no decimals?