2

我正在使用 pandas Styler 类将某些列格式化为百分比。当我将输出写入 excel 时,列仍显示为浮点数。为什么我能够正确格式化和保存颜色,但不能正确设置百分比?

import pandas as pd
import numpy as np

def color_negative_red(val):
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],axis=1)

这会产生:

df.style.format('{:.2%}').applymap(color_negative_red)

格式化数据框

但是保存到 excel 会将百分比恢复为浮点数:

df.style.format('{:.2%}').applymap(color_negative_red).to_excel('format_test.xlsx')

Excel 输出

该怎么办?

4

2 回答 2

0

百分比格式的建议解决方法:

with pd.ExcelWriter('test_format.xlsx') as writer:
    df.to_excel(writer, sheet_name='Sheet1', index=False)
    percent_format = writer.book.add_format({'num_format': '0.00%'})
    worksheet = writer.book.worksheets_objs[0]
    for col in ['A','C','E']:
        worksheet.set_column(f'{col}:{col}', None, percent_format)

确实将百分比添加到 A、C 和 E 列。

具有百分比格式的工作表

但是,它仅适用于 DataFrame 对象,不能与 Styler 一起使用,这意味着,所有其他格式都需要使用 writer 对象完成:

with pd.ExcelWriter('test_format.xlsx') as writer:
    df.style.applymap(color_negative_red).to_excel(writer, sheet_name='Sheet1', index=False)
    percent_format = writer.book.add_format({'num_format': '0.00%'})
    worksheet = writer.book.worksheets_objs[0]
    for col in ['A','C','E']:
        worksheet.set_column(f'{col}:{col}', None, percent_format)

在此处输入图像描述

于 2020-05-28T08:49:14.860 回答
0

您可能想看看openpyxl,例如通过这个线程 在 Excel 中使用 Pandas 编写百分比

于 2020-05-27T14:05:26.720 回答