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

如何为Pandas DataFrame指定列设置背景色并保存为CSV/Excel

DataFrame列组按条件着色解决方案

原始数据与需求

待处理DataFrame

import numpy as np
import pandas as pd

data = {
    'ID1': [1, 1, 2, 4],
    'ID2': [1, 2, 1, 1],
    'A': [1, 2, 3, np.nan],
    'B': [4, 5, 6, ''],
    'C': [1, 2, 3, 4],
    'D': [4, 5, 6, 7],
    'E': [1, 2, 3, np.nan],
    'F': [4, 5, 6, 7]
}
df = pd.DataFrame(data)

着色规则

列分组为[A,B]、[C,D,E,F],按行判断:

  • 列组内所有值相等 → 背景设为浅绿(lightgreen)
  • 值不相等 → 背景设为浅珊瑚色(lightcoral)
  • 列组内存在空值(null)或空白('')→ 背景设为黄色(yellow)

原代码问题分析

原代码错误地直接修改df[col_set]的数值内容,而Pandas设置单元格样式需通过Styler对象实现,不能直接赋值样式字符串到数据列。

正确实现代码

column_set = [['A','B'],['C','D','E','F']]

def highlight_groups(row):
    # 初始化样式列表,默认无样式
    styles = [''] * len(row)
    # 遍历每个列组
    for cols in column_set:
        group_data = row[cols]
        # 检查空值或空白
        has_null = group_data.isnull().any()
        has_blank = group_data.eq('').any()
        
        if has_null or has_blank:
            # 标记黄色背景
            for col in cols:
                styles[row.index.get_loc(col)] = 'background-color: yellow'
        else:
            # 检查组内值是否全部相等
            unique_vals = group_data.unique()
            if len(unique_vals) == 1:
                for col in cols:
                    styles[row.index.get_loc(col)] = 'background-color: lightgreen'
            else:
                for col in cols:
                    styles[row.index.get_loc(col)] = 'background-color: lightcoral'
    return styles

# 应用样式并输出
styled_df = df.style.apply(highlight_groups, axis=1)
# 若需导出到Excel:styled_df.to_excel('styled_result.xlsx', engine='openpyxl')
styled_df

关键说明

  1. 使用df.style.apply()方法绑定样式处理函数,axis=1指定逐行处理
  2. 优先判断空值/空白条件,避免空值干扰值相等的判断
  3. 通过row.index.get_loc(col)定位列的索引位置,精准设置对应单元格样式
  4. 最终返回的styled_df为Styler对象,可直接在Jupyter环境显示,或导出为带样式的Excel文件

内容的提问来源于stack exchange,提问作者Sweta Rawani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 06:14:55