You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 01:55:11