python - 将不同列的不同格式的 pandas DataFrame 写入 Excel

标签 python excel pandas openpyxl

我正在尝试将 pandas DataFrame 写入 .xlsx 文件,其中不同的数字列将具有不同的格式。例如,有些只显示两位小数,有些不显示,有些会格式化为带“%”符号的百分比等。

我注意到 DataFrame.to_html() 有一个 formatters 参数,它允许人们这样做,将不同的格式映射到不同的列。但是,DataFrame.to_excel() 方法上没有类似的参数。我们拥有的最多的是一个对所有数字都是全局的 float_format

我已经阅读了许多至少部分与我的问题相关的 SO 帖子,例如:

pandas API 中是否有其他更方便的 Excel 相关函数/属性可以在这里提供帮助,或者在 openpyxl 上有类似的东西,或者可能有一些方法可以直接在每一列上指定输出格式元数据DataFrame 然后将由不同的输出器在下游解释?

最佳答案

您可以使用 Pandas 0.16 和 XlsxWriter 引擎通过访问底层工作簿和工作表对象来执行此操作:

import pandas as pd

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

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter objects from the dataframe writer object.
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%'})
format3 = workbook.add_format({'num_format': 'h:mm:ss AM/PM'})

# 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)

worksheet.set_column('D:D', 16, format3)

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

输出:

enter image description here

另见 Working with Python Pandas and XlsxWriter .

关于python - 将不同列的不同格式的 pandas DataFrame 写入 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29974672/

相关文章:

python - Pandas 按 2 列分组,使用另一列查找增量

python - 从 stomp API 设置预取限制

python - CsvReader 下一个函数

python - 在 32 位库中使用 python ctypes

excel - 当我计算文本的行数时,为什么结果为 1?

python - 合并两个不完全匹配时间戳的 pandas 数据帧

原始模式下的Python stdin 打印添加空格

java - 在 Java 中导出到 CSV/Excel

vba - 更改 Word 文档中所有链接的来源 - 范围错位

python - 如何动态地将多个数据帧附加在一起?