gpt4 book ai didi

excel - Pandas :to_excel() float_format

转载 作者:行者123 更新时间:2023-12-02 07:48:25 25 4
gpt4 key购买 nike

我试图让 float_format 参数与 pandas 的 to_excel() 函数一起使用,但它似乎没有做任何事情。

代码:

df = pd.DataFrame({
'date':['1/15/2016','2/1/2016','2/15/2016','3/15/2016'],
'numA':[1000,2000,3000,4000.3],
'numB':[10000,20000.2,30000,40000]
})

writer = pd.ExcelWriter('c:/.../pandas_excel_test.xlsx', engine = 'xlsxwriter')

print df.dtypes

df.to_excel(writer,
index = False,
float_format = '%.2f',
)

但 Excel 文件如下所示:

enter image description here

我确认数据类型为:

date     object
numA float64
numB float64
dtype: object

有人知道如何在to_excel()中正确设置 float 格式吗?

最佳答案

我相信 Excel 格式会改变 float 的显示方式。我尝试了 to_csv 方法,并且 float_format 有效。对于 Excel,告诉 Excel 如何显示列有帮助:

df = pd.DataFrame({
'date':['1/15/2016','2/1/2016','2/15/2016','3/15/2016'],
'numA':[1000,2000,3000,4000.3],
'numB':[10000,20000.2,30000,40000]
})

writer = pd.ExcelWriter('c:/.../pandas_excel_test.xlsx', engine = 'xlsxwriter')
df.to_excel(writer, index=False, sheet_name='Sheet1')
workbook = writer.book
worksheet = writer.sheets['Sheet1']
format1 = workbook.add_format({'num_format': '0.00'})
worksheet.set_column('C:C', None, format1) # Adds formatting to column C
writer.save()

结果:

Final excel result

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

关于excel - Pandas :to_excel() float_format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44423036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com