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

如何删除pandas面板时间序列MultiIndex中观测数不足的country ID索引

实现筛选逻辑的两种常用方法

方法1:使用groupby.filter(写法简洁直观,适合中小数据集)

直接对country ID层级分组,保留组内观测数≥2的分组即可:

import pandas as pd
import numpy as np

# 示例数据构造代码
arrays = [['country i', 'country i', 'country i', 'country j', 'country j', 'country j', 'country e'], 
[1999,2000,2001,1999,2000,2001,2000]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=["country ID", "year"])
dfx = pd.Series(np.random.randn(7), index=index)

# 核心筛选代码
filtered_dfx = dfx.groupby(level="country ID").filter(lambda g: len(g) >= 2)

运行后输出的filtered_dfx结果如下,已自动删除只有1条记录的country e:

country ID  year
country i   1999    0.572030
            2000    1.736893
            2001   -1.213016
country j   1999    0.167581
            2000   -1.178015
            2001   -1.470233
dtype: float64

方法2:使用布尔索引(运行效率更高,适合百万级以上的大数据集)

先给每一行匹配对应国家的总观测数,再用布尔条件筛选:

# 计算每个country ID的观测数,广播到所有对应行
country_obs_count = dfx.groupby(level="country ID").transform("count")
# 布尔筛选
filtered_dfx = dfx[country_obs_count >= 2]

两种方法输出结果完全一致,可根据数据集规模选择合适的写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:27:05