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

如何按规则高亮Pandas DataFrame指定行的数据

问题解决:Pandas DataFrame 高亮指定行数据

错误原因分析

你遇到的ValueError是因为:

  • 你生成的highlight是一个仅对应5列的Series,但df.style.apply()默认按行(axis=0)处理,要求返回结果的形状必须与原DataFrame的行结构匹配(10行×5列)。
  • 直接返回固定的highlight会导致返回结果的索引/形状与原DataFrame不匹配,触发报错。

正确实现方案

我们需要针对索引1-5的行单独应用高亮规则,其他行保持无样式。以下提供两种实现方式:

方式1:逐行处理(直观易读)

import pandas as pd
import numpy as np

# 构造你的DataFrame
data = {
    'A-A': [0.37, 0.39, 0.35, 0.35, 0.36, 0.34, 0.35, 0.33, 0.36, 0.33],
    'A-B': [10.24, 10.26, 10.22, 10.23, 10.19, 10.25, 10.20, 10.17, 10.25, 10.17],
    'A-C': [5.02, 5.04, 5.00, 5.05, 5.07, 5.03, 5.08, 5.05, 5.08, 5.03],
    'A-D': [0.63, 0.65, 0.63, 0.65, 0.67, 0.66, 0.69, 0.62, 0.69, 0.62],
    'A-E': [20.30, 20.32, 20.28, 20.45, 20.25, 20.33, 20.22, 20.40, 20.45, 20.22]
}
index = ['Tg', 'USL', 'LSL', 1, 2, 3, 4, 5, 'Max', 'Min']
df = pd.DataFrame(data, index=index)

# 定义高亮函数
def highlight_target_rows(row):
    # 提取基准值:USL、LSL、Max、Min
    usl = df.loc['USL']
    lsl = df.loc['LSL']
    max_val = df.loc['Max']
    min_val = df.loc['Min']
    
    # 初始化样式列表,默认无样式
    styles = [''] * len(row)
    
    # 仅处理索引1-5的行
    if row.name in [1,2,3,4,5]:
        for idx, col in enumerate(row.index):
            # 按规则匹配样式
            if max_val[col] > usl[col] or min_val[col] < lsl[col]:
                styles[idx] = 'background-color: red'
            elif max_val[col] == usl[col] or min_val[col] == lsl[col]:
                styles[idx] = 'background-color: yellow'
            else:
                styles[idx] = 'background-color: green'
    return styles

# 应用样式
df.style.apply(highlight_target_rows, axis=1)

方式2:向量化处理(高效适合大数据)

import pandas as pd
import numpy as np

# 构造DataFrame(同方式1)
data = {
    'A-A': [0.37, 0.39, 0.35, 0.35, 0.36, 0.34, 0.35, 0.33, 0.36, 0.33],
    'A-B': [10.24, 10.26, 10.22, 10.23, 10.19, 10.25, 10.20, 10.17, 10.25, 10.17],
    'A-C': [5.02, 5.04, 5.00, 5.05, 5.07, 5.03, 5.08, 5.05, 5.08, 5.03],
    'A-D': [0.63, 0.65, 0.63, 0.65, 0.67, 0.66, 0.69, 0.62, 0.69, 0.62],
    'A-E': [20.30, 20.32, 20.28, 20.45, 20.25, 20.33, 20.22, 20.40, 20.45, 20.22]
}
index = ['Tg', 'USL', 'LSL', 1, 2, 3, 4, 5, 'Max', 'Min']
df = pd.DataFrame(data, index=index)

# 创建空样式矩阵
style_matrix = pd.DataFrame('', index=df.index, columns=df.columns)

# 定义目标行和高亮条件
target_rows = [1,2,3,4,5]
red_condition = (df.loc['Max'] > df.loc['USL']) | (df.loc['Min'] < df.loc['LSL'])
yellow_condition = (df.loc['Max'] == df.loc['USL']) | (df.loc['Min'] == df.loc['LSL'])
green_condition = ~red_condition & ~yellow_condition

# 批量设置样式
style_matrix.loc[target_rows, red_condition] = 'background-color: red'
style_matrix.loc[target_rows, yellow_condition] = 'background-color: yellow'
style_matrix.loc[target_rows, green_condition] = 'background-color: green'

# 应用样式
df.style.apply(lambda row: style_matrix.loc[row.name], axis=1)

效果说明

  • 索引1-5的行中,符合Max > USL或Min < LSL的单元格会被标红
  • 符合Max == USL或Min == LSL的单元格会被标黄
  • 其余符合要求的单元格会被标绿
  • 非目标行(Tg、USL、LSL、Max、Min)保持无样式

内容的提问来源于stack exchange,提问作者A.E

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:06:18