问题描述
我正在尝试让 float_format
参数与 pandas 的 to_excel()
函数一起使用,但它似乎没有做任何事情.
代码:
df = pd.DataFrame({'日期':['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.dtypesdf.to_excel(作家,指数=假,float_format = '%.2f',)
但是 Excel 文件看起来像这样:
我确认 dtypes 为:
日期对象numA float64numB float64数据类型:对象
有谁知道如何正确格式化 to_excel()
中的浮点数?
我相信 Excel 格式会改变浮点数的显示方式.我尝试了 to_csv
方法并且 float_format
工作.对于 excel,告诉 excel 如何显示列有帮助:
df = pd.DataFrame({'日期':['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')工作簿 = writer.book工作表 = writer.sheets['Sheet1']format1 = workbook.add_format({'num_format': '0.00'})worksheet.set_column('C:C', None, format1) # 将格式添加到 C 列writer.save()
结果:
更多信息:http://xlsxwriter.readthedocs.io/example_pandas_column_formats.htmlp>
I'm trying to get the float_format
parameter working with pandas' to_excel()
function, but it doesn't seem to do anything.
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:
I confirmed dtypes as:
date object
numA float64
numB float64
dtype: object
Does anyone know how to properly format floats in to_excel()
?
I believe Excel formatting changes how floats are displayed. I tried to_csv
method and float_format
worked. For excel, telling excel how to display the column helps:
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:
More info: http://xlsxwriter.readthedocs.io/example_pandas_column_formats.html
这篇关于 pandas :to_excel() float_format的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!