Python pandas dataframe和excel:添加单元格背景颜色

时间:2017-06-05 09:23:02

标签: python excel pandas dataframe

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

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

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

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

2 个答案:

答案 0 :(得分:3)

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

结果:

enter image description here

答案 1 :(得分:3)

您可以使用StyleFrame库来实现此目的。

安装

pip install styleframe

可以找到此库的文档here

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

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

干杯!