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

pandas DataFrame逐行对比数值并给符合条件单元格批量标色的实现方法

实现方案

步骤1:批量应用对比逻辑到所有目标列

直接对需要处理的列批量生成对比结果,代码如下:

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({'Value1': [1, 3, 3, 1, 2, 3, 2, 5, 6, 1],
                   'Value2': [3, 1, 2, 3, 2, 5, 6, 1, 2, 3],
                   'Value3': [3, 2, 4, 6, 7, 5, 4, 3, 2, 1]})

# 筛选需要处理的目标列(也可以手动指定列表如['Value1','Value2','Value3'])
target_cols = [col for col in df.columns if col.startswith('Value')]

# 批量生成各列的对比结果列
for col in target_cols:
    df[f'{col}_match'] = df[col].gt(df[col].shift(-1, fill_value=-1))

运行后会自动为每个Value列生成对应的xxx_match布尔列,逻辑和你之前单列的实现完全一致。

步骤2:给符合条件的单元格添加背景色

用pandas内置的Styler实现条件着色,以下代码实现当前行值大于下一行的原数值单元格标黄色,对应的match列True值标绿色的效果,可根据需求调整颜色值:

def highlight_cells(s):
    # 处理原Value列:符合对比条件的标黄色
    if s.name in target_cols:
        is_match = df[f'{s.name}_match']
        return ['background-color: yellow' if v else '' for v in is_match]
    # 处理match列:值为True的标绿色
    elif '_match' in s.name:
        return ['background-color: lightgreen' if v else '' for v in s]
    # 其他列无样式
    else:
        return ['' for _ in s]

# 应用样式,Jupyter环境可直接渲染显示着色效果
styled_df = df.style.apply(highlight_cells)
# 如需导出带样式的Excel,执行下面的代码即可
# styled_df.to_excel('highlighted_result.xlsx', engine='openpyxl', index=False)

效果说明

  • 所有满足「当前行数值 > 下一行同列数值」的原数值单元格会自动填充黄色背景
  • 对应的match列中值为True的单元格会填充浅绿色背景
  • 导出到Excel文件时样式会完整保留,无需额外调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:09:05