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

如何在DataFrame中对比两列值并为指定列单元格设置背景色

解决方法

要实现「对比petal_length与对应行sepal_width的值,给petal_length列设置背景色(值更小则红,否则绿)」的需求,你需要修改原有的样式逻辑——因为要同时访问同一行的两列数据,不能再用applymap(它仅处理单个单元格值),改用apply方法来处理整行数据。

完整代码如下:

import pandas as pd
import seaborn as sns

# 加载并采样数据集
iris = sns.load_dataset('iris')
df = iris.sample(n=10, random_state=1)

# 定义新的高亮函数
def highlight_petal_length(row):
    # 初始化所有列的样式为空(无背景色)
    style_list = [''] * len(row)
    # 获取petal_length列在当前行的索引位置
    petal_col_pos = row.index.get_loc('petal_length')
    # 对比两列值,设置对应样式
    if row['petal_length'] < row['sepal_width']:
        style_list[petal_col_pos] = 'background-color: red'
    else:
        style_list[petal_col_pos] = 'background-color: green'
    return style_list

# 应用样式,axis=1表示按行处理
df.style.apply(highlight_petal_length, axis=1)

核心要点:

  • 使用apply(..., axis=1)让函数接收整行数据,这样才能同时拿到petal_length和sepal_width的值做对比。
  • 函数中先创建与行长度匹配的空样式列表,只修改petal_length对应的位置,确保其他列不受影响。
  • 通过row.index.get_loc()获取目标列的索引,保证样式精准作用在petal_length列上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:05:44