简体   繁体   English

熊猫在将DataFrame导出到CSV时如何保持LAST尾随零

[英]Pandas how to keep the LAST trailing zeros when exporting DataFrame into CSV

In this question, my goal is to preserve the last trailing zeros when exporting the DataFrame to CSV 在这个问题中,我的目标是在将DataFrame导出到CSV时保留最后的 尾随 zeros

My dataset looks like this: 我的dataset如下所示:

EST_TIME    Open    High
2017-01-01  1.0482  1.1200    
2017-01-02  1.0483  1.1230
2017-01-03  1.0485  1.0521
2017-01-04  1.0480  1.6483
2017-01-05  1.0480  1.7401
...., ...., ....
2017-12-31  1.0486  1.8480

I import and create a DataFrame and save to CSV by doing this: 我通过执行以下操作导入并创建一个DataFrame并保存为CSV:

df_file = '2017.csv'
df.to_csv(df_file, index=False)
files.download(df_file)

When I view the CSV, I see this: 当我查看CSV时,会看到以下内容:

EST_TIME    Open    High
2017-01-01  1.0482  1.12   
2017-01-02  1.0483  1.123
2017-01-03  1.0485  1.0521
2017-01-04  1.048   1.6483
2017-01-05  1.048   1.7401
...., ...., ....
2017-12-31  1.0486  1.848

All the zeros at the end are gone. 最后的所有零都消失了。 I want to preserve the trailing zeros when I save the CSV and I want it at 4 decimal place. 保存CSV时我想保留尾随零,并将其保留在小数点后4位。

Could you please let me know how can I achieve this? 您能告诉我如何实现吗?

You could call apply and use format as such before writing to csv: 您可以在写入csv之前调用apply和use format这样的format

df_file = '2017.csv'
df['Open'] = df['Open'].apply('{:0<6}'.format)
df['High'] = df['High'].apply('{:0<6}'.format)
df.to_csv(df_file, index=False)

To apply to all columns, you can use applymap : 要应用于所有列,可以使用applymap

df = df.applymap('{:0<6}'.format)

Hope this helps. 希望这可以帮助。

Try this: Float format both to display your data with 4 decimal places and to save it with 4 decimal. 尝试以下操作:浮点格式既要以小数点后四位显示数据,又要以小数点后四位保存数据。

when reading to pandas: 读大熊猫时:

pd.options.display.float_format = '{:,.4f}'.format

when saving to CSV. 保存为CSV时。

df.to_csv('your_file.csv', float_format='%.4f',index=False)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM