假设我在 pandas 中编写这段代码来创建一个数据框:
pd.DataFrame({'x':random.sample(range(1,100), 4),
'y':random.sample(range(1,100), 4),
'z':random.sample(range(1,100), 4)},
index = [['a1', 'b1', 'c1','d1'], ['a2', 'b2', 'c2', 'd2']])
这会产生以下数据框:
x y z
a1 a2 8 2 85
b1 b2 43 93 58
c1 c2 1 46 24
d1 d2 60 37 62
我想通过传递如下列表来选择多索引行:
[[a1, a2], [b1, b2], [c1, c2]]
返回:
x y z
a1 a2 8 2 85
b1 b2 43 93 58
c1 c2 1 46 24
pandas 中是否有函数可以做到这一点?
最佳答案
您非常接近:您需要将索引定义为元组列表而不是列表列表:
target_index = [('a1', 'a2'), ('b1', 'b2'), ('c1', 'c2')]
然后
df.loc[target_index]
给你想要的输出:
x y z
a1 a2 0 2 3
b1 b2 1 3 4
c1 c2 2 4 5
关于python - 多索引数据框中的多行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40666466/