简体   繁体   English

Python Pandas:强制将df保存在4位数的csv数值中

[英]Python Pandas: force to save a df in a csv numerical values with 4 digits

I have a dataframe which have float numbers and I would like to save it with the same number of digits. 我有一个具有浮点数的数据帧,我想用相同的位数保存它。 This is my dataframe df : 这是我的数据帧df

       1     0.917007  0.920562  0.922801  0.922745  0.917396  0.922445   
       2     0.914374  0.926690  0.914257  0.914607  0.914462  0.910307   
       3     0.919565  0.907405  0.916554  0.916463  0.919817  0.917184   
       4     0.912238  0.915469  0.900786  0.900752  0.912059  0.919894   
       5     0.906972  0.920995  0.918015  0.918200  0.908895  0.907092 

And I am saving it doing: 我正在保存:

from pandas import ExcelWriter
writer = ExcelWriter('PythonExport.xlsx')
table.to_excel(writer,'aName',float_format='%11.4f')
writer.save()

But when I open the file, I see this: 但是当我打开文件时,我看到了这个:

在此输入图像描述

How can I do to force the number of digits saved for each cell to get this?: 如何强制为每个单元格保存的位数才能得到这个?:

在此输入图像描述

Edit: same happening trying to save as a csv file with the following 编辑:同样发生尝试保存为具有以下的csv文件

table.to_csv('PythonExport.csv', sep=',',float_format='%11.4f')

Note: I'm using python3 注意:我正在使用python3

The following should work as described here 下面应该工作的描述在这里

df.applymap('{:.4f}'.format).to_csv('PythonExport.csv')

To verify make sure you open the .csv in a text editor and not Excel. 要验证确保在文本编辑器中打开.csv而不是Excel。

You need to create format and then add it to column wherever you need to add, this might help you. 您需要创建格式,然后将其添加到您需要添加的列中,这可能对您有所帮助。

df.to_excel(writer, sheet_name='Sheet1')
workbook  = writer.book
worksheet = writer.sheets['Sheet1']
format1 = workbook.add_format({'num_format': '0.0000'})
worksheet.set_column('B:B', None, format1)
writer.save()

More info: http://xlsxwriter.readthedocs.io/example_pandas_column_formats.html 更多信息: http//xlsxwriter.readthedocs.io/example_pandas_column_formats.html

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

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