Python pandas 数据框和 excel:添加单元格背景色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44365676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:44:07  来源:igfitidea点击:

Python pandas dataframe and excel: Add cell background color

pythonexcelpandasdataframe

提问by asdfkjasdfjk

Currently I save my dataframe like this

目前我像这样保存我的数据框

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

And resulted excel file looks like this

结果excel文件看起来像这样

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 ...

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?

我需要的是,当 cus value == header value 时,该单元格应具有绿色背景。在上面的示例中,所有值为“col”的单元格都应设置为绿色背景。我怎样才能做到这一点?

回答by crazyglasses

You can use the StyleFrame library to achieve this.

您可以使用 StyleFrame 库来实现这一点。

To install

安装

pip install styleframe

The documentation of this library can be found here.

这个库的文档可以在这里找到。

Try the following code to check whether it works to serve your purpose.

尝试以下代码以检查它是否可以满足您的目的。

import pandas as pd
from StyleFrame import StyleFrame, Styler

df = pd.DataFrame(" Your Dataframe ")

sf = StyleFrame(df)
style = Styler(bg_color='green') 
for col_name in df.columns:
    sf.apply_style_by_indexes(sf.loc[sf['col_name']== col_name ], cols_to_style=col_name,
                          styler_obj=style)
sf.to_excel('test.xlsx').save()

Cheers!

干杯!

回答by MaxU

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

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')

Result:

结果:

enter image description here

在此处输入图片说明