我正在使用具有两级索引的数据框。第一级用于项目名称,第二级用于项目颜色。在我的第二级索引中,我总是有一个名为“total”的索引名称,用于表示所有颜色的总和。
我想以 python 返回所有鞋子的“总计”值的方式查询数据框。我可以重新排序索引,但我正在寻找更干净的解决方案。我怎么能这样做呢?
我认为可能有帮助的是链接索引的“空白”术语。这样的东西可能已经存在了吗?
例如
df.loc[*blank*,"total",:]
最佳答案
我认为您需要 :
和 IndexSlice
来选择所有值:
arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux', 'bar', 'foo']),
np.array(['one','two','one','two','total','two','total', 'two','total','four'])]
df = pd.DataFrame(np.random.randn(10), index=arrays)
print (df)
0
bar one -0.152506
two -0.492401
baz one -1.528111
two -3.284650
foo total -0.346641
two 0.630630
qux total -0.232299
two 0.361744
bar total -2.170350
foo four -2.332996
idx = pd.IndexSlice
df1 = df.loc[idx[:,"total"],:]
print (df1)
0
foo total -0.346641
qux total -0.232299
bar total -2.170350
<小时/>
或者使用DataFrame.xs
:
df1 = df.xs('total', level=1)
print (df1)
0
foo -0.099117
qux 0.381831
bar 1.638784
df1 = df.xs('total', level=1, drop_level=False)
print (df1)
0
foo total -0.570454
qux total 0.015090
bar total -1.084960
关于python - 在 pandas multiindex 中填充 "blank"值以访问较低级别的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53171453/