如何为多级索引表格的PP列单元格设置背景色并导出Excel
多级索引DataFrame中仅为指定层级列设置单元格背景色并导出Excel
问题场景
有如下多级列索引的DataFrame:
None INT INT INT PP PP PP DATE 2021-12-01 2021-12-02 2021-12-03 2021-12-04 2021-12-05 2021-12-06 0 1.0 0.0 2.0 2.0 4.0 2.0 1 NaN NaN NaN NaN NaN NaN 2 0.0 0.0 2.0 0.0 3.0 4.0 3 0.0 2.0 2.0 2.0 3.0 2.0 4 0.0 0.0 0.0 0.0 0.0 0.0 5 0.0 0.0 0.0 0.0 0.0 0.0 6 0.0 0.0 0.0 0.0 0.0 0.0 7 2.0 1.0 0.0 1.0 2.0 0.0 8 NaN NaN NaN NaN NaN NaN 9 0.0 0.0 0.0 0.0 0.0 0.0
需求是仅为第一层级为PP的列,根据单元格值设置背景色(0=白色,1=浅灰色,2=灰色,3=黄色,4=橙色,5=红色,其他=黑色),同时保留多级索引结构并导出到Excel。原代码因多级索引调用方式错误、整行着色逻辑不符合需求,无法正常运行。
解决方案
方法一:使用applymap配合精准列定位
这是最简洁的实现方式,通过subset参数精准锁定PP列,再对每个单元格应用颜色规则:
import pandas as pd # 定义颜色规则函数 def set_pp_colors(val): if pd.isna(val): return '' # NaN值不设置背景色 if val == 0: return 'background-color: white' elif val == 1: return 'background-color: lightgray' elif val == 2: return 'background-color: gray' elif val == 3: return 'background-color: yellow' elif val == 4: return 'background-color: orange' elif val == 5: return 'background-color: red' else: return 'background-color: black' # 仅对第一层级为PP的列应用样式 styled_df = df.style.applymap(set_pp_colors, subset=pd.IndexSlice[:, 'PP']) # 导出Excel,保留多级索引 styled_df.to_excel('ROUTE/name_of_thefile.xlsx', engine='openpyxl', index=True)
代码说明
pd.IndexSlice[:, 'PP']:在多级列索引中定位所有行+第一层级为PP的列,实现精准范围选择applymap:针对每个单元格单独应用样式函数,配合subset仅修改目标列- 增加
pd.isna(val)判断,避免空值被错误着色
方法二:使用apply按列处理
如果习惯按列逻辑编写代码,可通过判断列名层级实现:
import pandas as pd def color_pp_column(col): # 非PP列返回空样式,不修改 if col.name[0] != 'PP': return [''] * len(col) # 对PP列应用颜色规则 return [ 'background-color: white' if val == 0 else 'background-color: lightgray' if val == 1 else 'background-color: gray' if val == 2 else 'background-color: yellow' if val == 3 else 'background-color: orange' if val == 4 else 'background-color: red' if val == 5 else 'background-color: black' if not pd.isna(val) else '' for val in col ] # 按列应用样式函数 styled_df = df.style.apply(color_pp_column, axis=0) styled_df.to_excel('ROUTE/name_of_thefile.xlsx', engine='openpyxl', index=True)
内容的提问来源于stack exchange,提问作者Javier
相关产品推荐
相关产品推荐

