如何为DataFrame分组行循环设置背景色并导出至Excel?
按物种分组循环设置整行背景色并导出Excel的解决方案
实现步骤与代码
import pandas as pd # 加载数据集 iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv') # 定义要循环使用的两种背景色(可根据需求替换) color_palette = ['#ffeeee', '#eef5ff'] # 为每个唯一物种分配循环颜色 unique_species = iris['species'].unique() color_mapping = { species: color_palette[idx % len(color_palette)] for idx, species in enumerate(unique_species) } # 定义整行上色的样式函数 def style_row(row): # 根据当前行的species获取对应颜色 bg_color = color_mapping[row['species']] # 返回与行中列数一致的样式列表,实现整行上色 return [f'background-color: {bg_color}'] * len(row) # 应用样式并导出到Excel styled_iris = iris.style.apply(style_row, axis=1) # 需要安装openpyxl:pip install openpyxl styled_iris.to_excel('iris_grouped_colored.xlsx', engine='openpyxl', index=False)
关键细节说明
- 适配未知分组数量:通过
unique()获取所有物种分组,利用取模运算idx % len(color_palette)实现颜色循环,不管有多少个分组都能自动交替应用两种颜色 - 整行样式设置:
apply函数指定axis=1后会逐行处理,返回与行长度匹配的样式列表,确保整行都应用背景色 - Excel导出兼容性:使用
openpyxl引擎才能正确保留样式,若未安装可通过pip install openpyxl安装
内容的提问来源于stack exchange,提问作者Yoda
相关产品推荐
相关产品推荐

