如何测试Pandas多索引中存在的一组值(并非全部)



应用于Pandas索引的isin()方法返回是否在传递的值集中找到每个索引值,但是否有可能只测试一组索引值?

在下面的multiIndex中,我想测试是否存在级别名称为s1、级别值为E、级别名称为d1、级别值future的索引。问题是,我测试的索引值可能不存在,所以像xsloc这样的选择方法不起作用。

df_routes.index
MultiIndex([('E', 'future',       'B', 'future'),
('E', 'future',       'B5', 'future'),
('E', 'future',       'B',   'spot'),
('B', 'future',       'B', 'future'),
('B', 'future',       'B5', 'future'),
('B', 'future',       'B',   'spot')],
names=['s1', 'd1', 's2', 'd2'])

我的问题是,当使用any作为索引值时,isin()返回False:

df_routes.index.isin([('E', 'future', any, any)])
array([False, False, False, False, False, False])

期望的结果是:

array([True, True, True, False, False, False])

这里有一个类似的问题,但答案只适用于索引,而不适用于多索引。

我该怎么做?

如果您想使用多索引过滤数据帧,只需使用.loc

df.loc[('E', 'future')]

示例数据帧

0
s1 d1     s2 d2
E  future B  future  1
B5 future  2
B  spot    3
B  future B  future  4
B5 future  5
B  spot    6

Ouput

0
s2 d2
B  future  1
B5 future  2
B  spot    3

创建布尔数组

(df.index.get_level_values(0) == 'E') & (df.index.get_level_values(1) == 'future')

相关内容

最新更新