使用DataFrame.to_excel后,Pandas ExcelWriter set_column无法格式化数字

时间:2015-05-12 17:24:38

标签: python excel pandas

我已尝试在http://xlsxwriter.readthedocs.org/en/latest/example_pandas_column_formats.html

的xlsxwriter网页上找到的示例代码
import pandas as pd

# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Numbers':    [1010, 2020, 3030, 2020, 1515, 3030, 4545],
                   'Percentage': [.1,   .2,   .33,  .25,  .5,   .75,  .45 ],
})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter("pandas_column_formats.xlsx", engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add some cell formats.
format1 = workbook.add_format({'num_format': '#,##0.00'})
format2 = workbook.add_format({'num_format': '0%'})

# Note: It isn't possible to format any cells that already have a format such
# as the index or headers or any cells that contain dates or datetimes.

# Set the column width and format.
worksheet.set_column('B:B', 18, format1)

# Set the format but not the column width.
worksheet.set_column('C:C', None, format2)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

但是它没有按预期格式化列 - 它们只是看起来没有格式化(没有数字舍入,百分比。)

我正在使用Pandas 0.15.2。有任何想法吗。这最近是在熊猫队改变了吗?

欢迎任何想法。

1 个答案:

答案 0 :(得分:1)

这似乎已在Pandas 16中修复。请参阅https://github.com/jmcnamara/XlsxWriter/issues/204