我有一个这种形式的数据框:
first bar foo
second one two three one two three
0 -2.008137 0.505892 -0.671299 -1.289395 -1.087887 -0.146657
1 -0.786329 -0.501268 -1.454408 2.627911 0.689416 -0.877968
2 -0.697007 0.929783 0.181715 0.533407 0.117859 -0.557975
3 -1.276656 -0.405381 -0.674329 0.117411 1.536421 0.040912
我想选择带有基于一级名称的索引的数据,如下所示:
selected = data.xs(('bar', 'two'), level = ['first','second'], axis=1)
这有效。但是,我想以这种方式选择多个标签。像这样的东西:
selected = data.xs(('bar', ['one','two']), level = ['first','second'], axis=1)
为了获得:
first bar
second one two
0 -2.008137 0.505892
1 -0.786329 -0.501268
2 -0.697007 0.929783
3 -1.276656 -0.405381
但是,这不起作用。如何以这种方式优雅地选择数据?重要的是我可以使用级别名称(“第一”和“第二”)。
最佳答案
您可以使用查询
方法,但需要进行转置
data.T.query('first in ["bar", "foo"] and second in ["one", "two"]').T
# ⤷ transpose here transpose back ⤴
或者您可以在查询
之外设置这些变量并引用它们
first = ['bar', 'foo']
second = ['one', 'two']
data.T.query('first in @first and second in @second').T
# ⤷ transpose here transpose back ⤴
这里有一个较少使用的替代方案来解决这个问题
data.filter(regex='one|two')
关于python - 从 MultiIndex 数据框中获取具有命名标签的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41809118/