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

如何对Pandas分组生成的MultiIndex DataFrame按双索引筛选子集?

如何在多级索引DataFrame中同时筛选分组与日期

你有一个通过groupby和pd.Grouper按月分组生成的多级索引DataFrame,结构如下:

Commitment ID
Team by product        Commitment Due Date               
A                      2016-11-30                       2
                       2017-04-30                       2
                       2018-01-31                      16
                       2019-09-30                      35
                       2020-04-30                      29
                       2020-11-30                     202
                       2020-12-31                      35
                       2021-01-31                      20
                       2021-09-30                       1
                       2021-10-31                       1
                       2022-06-30                      11
                       2022-07-31                       5
                       2022-08-31                       1
                       2022-09-30                      10
                       2022-10-31                      66
                       2022-11-30                       6
                       2022-12-31                      53
B                      2021-03-31                       1
                       2021-10-31                      11
                       2022-06-30                       1
                       2022-07-31                       3
                       2022-09-30                       1
                       2022-10-31                       1
                       2022-11-30                       2
                       2022-12-31                       1

目前你已经可以用byteammonths.loc[['A']]按Team by product筛选子集,现在需要同时按Commitment Due Date筛选,比如得到以下结果:

Commitment ID
Team by product        Commitment Due Date               
A                      2016-11-30                       2
                       2017-04-30                       2
                       2018-01-31                      16
                       2019-09-30                      35
                       2020-04-30                      29

解决方案

方法1:使用loc结合布尔掩码

先针对日期索引生成布尔条件,再结合分组筛选:

# 生成日期筛选的布尔掩码
date_mask = byteammonths.index.get_level_values('Commitment Due Date') <= '2020-04-30'
# 同时筛选Team A和符合条件的日期
result = byteammonths.loc[('A', date_mask), :]

方法2:使用pd.IndexSlice(更简洁直观)

借助pandas的IndexSlice工具,可以更清晰地指定多级索引的筛选范围:

import pandas as pd

# 创建索引切片对象
idx = pd.IndexSlice
# 筛选Team A且日期不晚于2020-04-30的行
result = byteammonths.loc[idx['A', :'2020-04-30'], :]

两种方法都能得到你需要的结果,其中IndexSlice的写法更适合复杂的多级索引筛选场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:48:21