Pandas Multiindex - 从列表中选择

时间:2017-03-25 06:58:44

标签: pandas

我有以下DataFrame,索引日期和ID

                  V1   V2
Date       ID
01.01.2010  1      x    y
01.01.2010  2      x    y
02.01.2010  1      x    y
        ......

我可以用

选择日期范围
df.loc[ slice(start, end) ]

但我需要根据ID列表过滤数据。例如

allowed = [1, 5]
df.loc[ allowed ]

这怎么可能?

2 个答案:

答案 0 :(得分:1)

使用index.isin检查索引轴的成员资格。在多索引的情况下,明确提供必须执行检查的级别或级别名称的位置。

df.loc[df.index.isin(allowed, level='ID')]    # level name is specified

(OR)

df.loc[df.index.isin(allowed, level=1)]       # level position is specified

答案 1 :(得分:1)

您还可以使用.query()方法:

In [62]: df
Out[62]:
              V1 V2
Date       ID
2010-01-01 1   x  y
           2   x  y
2010-02-01 1   x  y

In [63]: allowed = [1, 5]

In [64]: df.query("ID in @allowed")
Out[64]:
              V1 V2
Date       ID
2010-01-01 1   x  y
2010-02-01 1   x  y
相关问题