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

pandas DataFrame如何为高于/低于列均值的单元格设置填充色

pandas实现DataFrame按列均值条件单元格着色

核心用pandas原生的Styler能力实现,不需要额外第三方库,逻辑是逐列计算均值后,给对应单元格匹配背景色样式。

完整实现代码

import pandas as pd
import numpy as np

def color_above_below_mean(col):
    # 计算当前列的均值
    col_avg = col.mean()
    # 初始化样式数组,默认无填充
    style_arr = np.array([''] * len(col), dtype=object)
    # 大于均值填充绿色
    style_arr[col > col_avg] = 'background-color: #4CAF50'
    # 小于均值填充红色
    style_arr[col < col_avg] = 'background-color: #F44336'
    # 等于均值/空值保留默认无填充
    return style_arr

# ------------------- 使用示例 -------------------
# 替换成你自己的DataFrame即可
df = pd.DataFrame({
    'col1': [12, 45, 23, 67, 31],
    'col2': [89, 72, 95, 61, 78],
    'col3': [2.1, 0.5, 3.3, 1.8, 4.2]
})

# 应用样式:axis=0代表逐列计算,subset指定仅对数值列生效
styled_table = df.style.apply(
    color_above_below_mean,
    axis=0,
    subset=df.select_dtypes(include=np.number).columns
)

使用说明

  • Jupyter Notebook/Lab环境下直接运行styled_table即可渲染出带颜色的表格
  • 需要导出带样式的Excel时,直接调用styled_table.to_excel('着色结果.xlsx', index=False)即可
  • 颜色可以自行修改色值调整深浅,比如把绿色换成lightgreen、红色换成lightcoral会更柔和
  • 如果你的表格全是数值列,可以去掉subset参数,直接写df.style.apply(color_above_below_mean, axis=0)即可
  • 空值、和列均值完全相等的值会保留默认无填充状态,符合需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 11:09:16