Python Pandas DataFrame和Excel:添加单元格背景色 [英] Python pandas dataframe and excel: Add cell background color

查看:2085
本文介绍了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?

推荐答案

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:添加单元格背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆