本文介绍了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:添加单元格背景色
发布评论