Pythonpandas数据框和Excel:添加单元格背景颜色
目前我保存像这样的数据框
writer = ExcelWriter('test.xlsx') test_df.to_excel(writer,'Sheet1') writer.save()
并导致excel文件看起来像这样
cus 1 abc 2 jbd 3 lkl ... 1 col vvvvv ... 2 vv col vvv ... 3 vvvv col v ...
我需要的是,当客户价值==标题值,该单元格应该有一个绿色的背景。 在上面的例子中,所有值为“col”的单元格都应该设置为绿色背景。 我怎样才能做到这一点?
您可以使用StyleFrame库来实现这一点。
安装
pip install styleframe
这个库的文档可以在这里find。
试试下面的代码来检查它是否可以满足你的目的。
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()
干杯!
Pandas 0.20.0中有一个新function – 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')
结果: