Skip to main content
 首页 » 编程设计

python之使用部分索引元组列表对多索引数据帧进行切片的最佳方法是什么

2024年11月01日17linjiqin

我想使用部分匹配的索引或元组列表对数据帧进行切片。

_ix = [('foo','a', 1), ('foo','a', 2), ('foo','b', 1),  
       ('foo','b', 2), ('foo','c', 1), ('foo','c', 2)] 
df = pd.DataFrame(np.ones((6, 1)), index=pd.MultiIndex.from_tuples(_ix)) 
print(df) 
 
           0 
foo a 1  1.0 
      2  1.0 
    b 1  1.0 
      2  1.0 
    c 1  1.0 
      2  1.0 

给定一个查询索引:

q_ix = [('foo', 'a'), ('foo', 'c')] 

我要获取

           0 
foo a 1  1.0 
      2  1.0 
    c 1  1.0 
      2  1.0 

我可以通过使用pd.concat 和列表推导得到这个...

df_sliced = pd.concat([df.loc[(*x, slice(None)), :] for x in q_ix]) 

...但是当我的查询索引很大时,这会非常笨拙。有没有更好的办法?

请您参考如下方法:

这是一种方式

df.reset_index(level=2).loc[q_ix].set_index('level_2',append=True) 
                 0 
      level_2      
foo a 1        1.0 
      2        1.0 
    c 1        1.0 
      2        1.0