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

如何基于多个二级标签选择Pandas多级索引DataFrame的列

在Pandas多级索引DataFrame中按多个二级标签选择列

嘿,我来帮你搞定这个多级列索引的选择问题!首先咱们先把你给出的示例DataFrame用代码还原出来,这样你可以直接运行测试:

import pandas as pd
import numpy as np

# 构建多级列索引
columns = pd.MultiIndex.from_tuples([
    ('bar', 'one'), ('bar', 'two'), ('baz', 'three'),
    ('baz', 'two'), ('foo', 'one'), ('foo', 'three'), ('qux', 'one')
])

# 构建DataFrame数据
data = np.array([
    [0.895717, 0.805244, -1.206412, 2.565646, 1.431256, 1.340309, -1.170299],
    [0.410835, 0.813850, 0.132003, -0.827317, -0.076467, -1.187678, 1.130127],
    [-1.413681, 1.607920, 1.024180, 0.569605, 0.875906, -2.211372, 0.974466]
])

df = pd.DataFrame(data, index=['A', 'B', 'C'], columns=columns)

运行完这段代码,你就能得到和示例一致的多级索引DataFrame了。接下来咱们看两种常用的方式,按多个二级标签筛选列:

方法1:用get_level_values + 布尔索引

这种方法的思路是先提取二级索引的所有值,然后判断每个值是否在你想要的标签列表里,最后用这个布尔数组来筛选列:

# 定义你想要选择的二级标签列表
target_second_level = ['one', 'two']

# 生成布尔索引:判断每个二级标签是否在目标列表中
mask = df.columns.get_level_values(1).isin(target_second_level)

# 筛选列
filtered_df = df.loc[:, mask]

运行后,filtered_df就会包含所有二级标签是one或two的列,也就是去掉了二级标签为three的那些列。

方法2:用pd.IndexSlice(更简洁推荐)

Pandas专门提供了IndexSlice来简化多级索引的筛选,写法更直观,尤其是当索引层级更多的时候:

idx = pd.IndexSlice

# 筛选所有行,二级标签为one或two的列
filtered_df = df.loc[:, idx[:, ['one', 'two']]]

这里的idx[:, ['one', 'two']]表示:一级索引不限制(选所有一级标签),二级索引只选one和two的列,是不是很清晰?

如果你的需求更复杂,比如想同时指定一级和二级标签的组合,也可以用IndexSlice,比如想选一级标签是bar且二级是one,或者一级是baz且二级是two的列,就可以这么写:

filtered_df = df.loc[:, idx[['bar', 'baz'], ['one', 'two']]]

这样就会精准筛选出符合组合条件的列啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:32:12