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

Pandas样式:基于绝对值为列设置背景渐变颜色

How to Apply Background Gradient Based on Absolute Deviation in Pandas DataFrame

Got it, let's work through this! You want your DataFrame's "A" column to have a background gradient where colors darken as values deviate absolutely from the target (6)—whether they're above or below that number. The core fix here is using absolute deviation instead of raw values to drive the gradient, which isn't the default behavior in Pandas Styler.

Step-by-Step Solution

Let's start with your sample data, then add the styling logic to match your Excel-like effect:

import pandas as pd

# Your original DataFrame
column1 = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
df = pd.DataFrame(data=column1, columns=["A"])

# Define your target value
target = 6

# Calculate absolute deviation from the target for each row
abs_deviation = abs(df["A"] - target)

# Apply the background gradient using the absolute deviation
styled_df = df.style.background_gradient(
    cmap="Blues",  # Swap for 'Reds', 'Greens', or any matplotlib colormap you prefer
    subset=["A"],  # Only apply this styling to the "A" column
    vmin=abs_deviation.min(),  # Lightest color at 0 deviation (value = 6)
    vmax=abs_deviation.max(),  # Darkest color at maximum deviation (7, for -1 and 12)
    gmap=abs_deviation  # Use absolute deviation to set color intensity (not raw values)
)

# Display the styled DataFrame (or export to Excel/HTML with styled_df.to_excel())
styled_df

Key Details Breakdown

  • gmap Parameter: This is the critical piece. Instead of using the original "A" column values to calculate the gradient, we pass abs_deviation—so color depth only depends on how far a value is from 6, not whether it's positive or negative.
  • Colormap Customization: cmap="Blues" gives a light-to-dark blue gradient, but you can swap this for any matplotlib colormap to match your desired look. If you want to replicate your exact Excel style, create a custom gradient:
    from matplotlib.colors import LinearSegmentedColormap
    
    # Create a gradient from white (no deviation) to your preferred dark color
    custom_cmap = LinearSegmentedColormap.from_list(
        "target_gradient", ["#ffffff", "#2c5f2d"], N=256  # Adjust hex codes to match your Excel sample
    )
    
    # Apply with the custom colormap
    styled_df = df.style.background_gradient(
        cmap=custom_cmap,
        subset=["A"],
        vmin=abs_deviation.min(),
        vmax=abs_deviation.max(),
        gmap=abs_deviation
    )
    

Export to Excel

If you want to save this styled DataFrame to Excel (matching your sample), run:

styled_df.to_excel("styled_data.xlsx", engine="openpyxl", index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:45:35