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

如何用不同层级的MultiIndex筛选Pandas多层索引DataFrame

如何用二级MultiIndex筛选三级索引的DataFrame?

我有一个包含三级索引(a, b, c)的DataFrame:

d
a b c   
1 9 4  1
2 8 2  4
3 7 5  2
4 6 4  5
5 5 6  3
6 4 5  6
7 3 7  4
8 2 6  7
9 1 8  5

同时有一个仅包含二级(a, b)的MultiIndex对象:

MultiIndex([(1, 9),
            (2, 8),
            (3, 7),
            (4, 6),
            (9, 1)],
           names=['a', 'b'])

尝试直接用df.loc[select_this]筛选时,会报错:

ValueError: operands could not be broadcast together with shapes (5,2) (3,) (5,2)

虽然可以通过重置索引实现需求:

selected = df1.reset_index('c').loc[select_this].set_index('c', append=True)

但希望避免额外的reset_index和set_index操作,以下是几种更直接的解决方案:

方法1:使用IndexSlice通配匹配

利用pandas.IndexSlice可以在多级索引中灵活指定筛选规则,通配符:表示匹配当前层级的所有值:

import pandas as pd

idx = pd.IndexSlice
selected = df1.loc[idx[select_this, :], :]

方法2:布尔索引+get_level_values

提取前两级索引,通过isin判断是否在目标MultiIndex中,生成布尔掩码筛选:

mask = df1.index.get_level_values(['a', 'b']).isin(select_this)
selected = df1[mask]

方法3:query方法(可读性优先)

将目标MultiIndex转为列表后,用query直接匹配元组条件:

tuples_list = select_this.to_list()
selected = df1.query('(a, b) in @tuples_list')

以上三种方法都能得到和重置索引相同的结果,且无需修改原DataFrame的索引结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:44:50