Python Pandas DataFrame和Excel:添加单元格背景色

编程入门 行业动态 更新时间:2024-10-28 13:24:27
本文介绍了Python Pandas DataFrame和Excel:添加单元格背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当前,我以这种方式保存数据框

Currently I save my dataframe like this

writer = ExcelWriter('test.xlsx') test_df.to_excel(writer,'Sheet1') writer.save()

生成的excel文件看起来像这样

And resulted excel file looks like this

cus 1 abc 2 jbd 3 lkl ... 1 col v v v v v ... 2 v v col v v v ... 3 v v v v col v ...

我需要的是,当cus value == header值时,该单元格应该具有绿色背景.在上面的示例中,所有值为"col"的单元格应设置为绿色背景.我该怎么办?

What I need is that, when cus value == header value, that cell should have a green background. In example above, all cells with value 'col' should be set green background. How can I do this?

推荐答案

有 Pandas 0.20.0-Excel output for styled DataFrames 中的一项新功能:

There is a new feature in Pandas 0.20.0 - Excel output for styled DataFrames:

styled = (df.style .applymap(lambda v: 'background-color: %s' % 'green' if v=='col' else '')) styled.to_excel('d:/temp/styled.xlsx', engine='openpyxl')

结果:

更多推荐

Python Pandas DataFrame和Excel:添加单元格背景色

本文发布于:2023-05-30 15:31:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/371052.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元格   背景色   Pandas   Python   Excel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!