pandas 熊猫:to_excel() float_format

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44423036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:44:47  来源:igfitidea点击:

Pandas: to_excel() float_format

excelpandasformatting

提问by elPastor

I'm trying to get the float_formatparameter working with pandas' to_excel()function, but it doesn't seem to do anything.

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

Code:

代码:

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',
    )

But the Excel file looks like this:

但 Excel 文件如下所示:

enter image description here

在此处输入图片说明

I confirmed dtypes as:

我确认 dtypes 为:

date     object
numA    float64
numB    float64
dtype: object

Does anyone know how to properly format floats in to_excel()?

有谁知道如何正确格式化浮点数to_excel()

采纳答案by Akshit Khurana

I believe Excel formatting changes how floats are displayed. I tried to_csvmethod and float_formatworked. For excel, telling excel how to display the column helps:

我相信 Excel 格式会改变浮点数的显示方式。我尝试了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()

Result:

结果:

Final excel result

最终的excel结果

More info: http://xlsxwriter.readthedocs.io/example_pandas_column_formats.html

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