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

Python中非唯一多级索引DataFrame的子集样式设置问题

Pandas多层索引DataFrame样式设置解决方案

场景复现

先构建示例多层索引DataFrame:

import numpy as np
import pandas as pd
import matplotlib.colors

arrays = [
    np.array(['Jack', 'Jack', 'Jack', 'Jack', 'Jack', 'Jack', 'Jack', 'Josh', 'Josh', 'Josh', 'Josh', 'Josh', 'Peter', 'Peter', 'Peter', 'Peter', 'Peter']),
    np.array(['Client A', 'Client A', 'Client A', 'Client A', 'Client B', 'Client B', 'Client B', 'Client C', 'Client C', 'Client D', 'Client D', 'Client D', 'Client E', 'Client E', 'Client E', 'Client E', 'Client E']),
    np.array(['Cars', 'Trains', 'Planes', 'Boats', 'Cars', 'Trains', 'Boats',  'Cars', 'Trains', 'Cars', 'Trains', 'Planes', 'Cars', 'Trains', 'Planes', 'Boats', 'Bikes'])
]
    
df = pd.DataFrame(np.random.randn(17, 5)+100, index=arrays)
df.columns = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
df.index.set_names(['Sales person', 'Client', 'Product'], inplace=True)

需求清单

  • 为Product为Cars的行添加横向背景渐变
  • 为Product为Trains的行添加文本渐变(先聚焦背景渐变实现)
  • 无数据单元格及索引中Cars单元格设灰色背景

原代码问题分析

原代码直接将df.loc[idx[:, :, 'Cars'], :]传入subset参数,不符合background_gradient对subset的要求(subset需要行列选择器,而非数据子集),因此触发FutureWarning且样式不生效。

修正后的解决方案

1. 实现Cars行的横向背景渐变

使用pd.IndexSlice正确指定subset的行范围,配合axis=1实现每行内的横向渐变:

idx = pd.IndexSlice
# 自定义渐变色彩映射
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("car_gradient", ["#ffcccc", "#ff6666"])

# 应用背景渐变,subset精准定位Product为Cars的所有行
styled_df = df.style.background_gradient(
    cmap=cmap,
    axis=1,
    subset=idx[:, :, 'Cars']
)

2. 设置索引中Cars单元格的灰色背景

通过set_table_styles针对多层索引的Product层级设置样式:

# 为索引层中值为Cars的单元格添加灰色背景
styled_df = styled_df.set_table_styles([
    {
        'selector': '.index_name_level2:contains("Cars")',
        'props': [('background-color', '#e0e0e0')]
    }
])

3. 处理无数据(NaN)单元格

如果DataFrame存在空值,添加灰色背景样式:

styled_df = styled_df.highlight_null(null_color='#e0e0e0')

4. 可选:Trains行的文本渐变实现

文本渐变需通过CSS实现,利用set_table_styles添加对应样式:

styled_df = styled_df.set_table_styles([
    {
        'selector': 'tr:has(.index_name_level2:contains("Trains")) td',
        'props': [
            ('background', '-webkit-linear-gradient(left, #ffd700, #ff8c00)'),
            ('-webkit-background-clip', 'text'),
            ('-webkit-text-fill-color', 'transparent')
        ]
    }
], overwrite=False)

查看最终效果

在Jupyter环境中直接调用变量即可渲染带样式的表格:

styled_df

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:40:32