在pandas中对数据进行排序后,我将其保存在Excel中.此时,我们正试图通过更改格式来提高可读性.我同时指定了数字格式和背景 colored颜色 ,但是只指定了其中一个时出现了错误.我很确定这不是一个错误,只是"我不是很理解".但我不知道我哪里犯了错.我想得到你的帮助.

下面是我编写的示例代码和运行它的结果.第一个代码是我格式化数字的时候.它工作正常.

df = pd.DataFrame({
    'Name': ['John', 'Isac'],
    'Value': [100000, 300000000]
})

with pd.ExcelWriter('test.xlsx', engine='xlsxwriter') as writer:
    df.to_excel(writer, sheet_name='test', index=False)
    
    workbook = writer.book
    worksheet = writer.sheets['test']
    
    format_with_commas = workbook.add_format({'num_format':'#,##0'})
    worksheet.set_column('B:B', 15, format_with_commas)

enter image description here

然而,问题是,如果您在此处编写代码来指定背景色,数字格式将不起作用.我已经将代码和执行结果作为图像包含在内.

df = pd.DataFrame({
    'Name': ['John', 'Isac'],
    'Value': [100000, 300000000]
})

styled_df = df.style.set_properties(**{'background-color':'yellow', 'color':'black'})

with pd.ExcelWriter('test.xlsx', engine='xlsxwriter') as writer:
    styled_df.to_excel(writer, sheet_name='test', index=False)
    
    workbook = writer.book
    worksheet = writer.sheets['test']
    
    format_with_commas = workbook.add_format({'num_format':'#,##0'})
    worksheet.set_column('B:B', 15, format_with_commas)

enter image description here

如果我的方法不正确,请告诉我哪里错了.或者,如果此代码过时,请也指出这一点.

推荐答案

我认为你只能使用Pandas 风格的解决方案,但如果勾选Styler.format:

使用输出格式Styler.to_EXCEL时会忽略Styler.Format,因为Excel和Python具有固有的不同格式 struct .但是,可以使用数字格式的伪css属性强制设置Excel允许的格式.请参见示例.

所以试一下number-format pseudo CSS attribute,见最后一段:

styled_df = df.style.set_properties(**{'background-color':'yellow', 'color':'black'})

pseudo_css = 'number-format: #,##0'

with pd.ExcelWriter('test.xlsx', engine='xlsxwriter') as writer:
    (styled_df.map(lambda  v: pseudo_css, subset=['Value'])
              .to_excel(writer, sheet_name='test', index=False))

对于更老的Pandas 版本:

styled_df = df.style.set_properties(**{'background-color':'yellow', 'color':'black'})

pseudo_css = 'number-format: #,##0'

with pd.ExcelWriter('test.xlsx', engine='xlsxwriter') as writer:
    (styled_df.applymap(lambda  v: pseudo_css, subset=['Value'])
              .to_excel(writer, sheet_name='test', index=False))

Python相关问答推荐

如何使用scikit-learn Python库中的Agglomerative集群算法以及集群中声明的对象数量?

Altair -箱形图边界设置为黑色,中线设置为红色

如何让pyparparsing匹配1天或2天,但1天和2天失败?

已删除的构造函数调用另一个构造函数

机器人与Pyton Minecraft服务器状态不和

通过交换 node 对链接列表进行 Select 排序

分组数据并删除重复数据

如何从具有多个嵌入选项卡的网页中Web抓取td类元素

TARete错误:类型对象任务没有属性模型'

比较两个数据帧并并排附加结果(获取性能警告)

如何标记Spacy中不包含特定符号的单词?

. str.替换pandas.series的方法未按预期工作

如何在Windows上用Python提取名称中带有逗号的文件?

优化pytorch函数以消除for循环

如何将Docker内部运行的mariadb与主机上Docker外部运行的Python脚本连接起来

Pre—Commit MyPy无法禁用非错误消息

关于Python异步编程的问题和使用await/await def关键字

所有列的滚动标准差,忽略NaN

无法在Docker内部运行Python的Matlab SDK模块,但本地没有问题

索引到 torch 张量,沿轴具有可变长度索引