在熊猫多索引中填充“空白”值以访问较低级别的索引

时间:2018-11-06 11:58:29

标签: python pandas indexing

我正在使用具有两级索引的数据框。第一级用于项目名称,第二级用于项目颜色。在第二级索引中,对于所有颜色的总和,我总是有一个名为“ total”的索引名称。

我想以python返回所有鞋子的“总计”值的方式查询数据帧。我可以重新排序索引,但是我正在寻找更清洁的解决方案。我该怎么办?

我认为可能有帮助的是将索引的“空白”术语链接起来的某种东西。这样的东西可能已经存在了吗?

例如

df.loc[*blank*,"total",:]

1 个答案:

答案 0 :(得分:2)

我认为您需要: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