我想使用部分匹配的索引或元组列表对数据帧进行切片。
_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
关于python - 使用部分索引元组列表对多索引数据帧进行切片的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57618525/