python - 从 MultiIndex 数据框中获取具有命名标签的列

标签 python pandas

我有一个这种形式的数据框:

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 ⤴

enter image description here


这里有一个较少使用的替代方案来解决这个问题

data.filter(regex='one|two')

enter image description here

关于python - 从 MultiIndex 数据框中获取具有命名标签的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41809118/

相关文章:

python - 在 scikit-learn 中可视化决策树

python - 如何在 python pandas 中获取多级索引中的一个系列

python - 为什么使用 .loc[] 访问 pandas 数据帧的列会产生重复的行?

python - 在 Python 中从包含特殊字符的 CSV 单元格中提取字符串

python - Pandas - 拆分列并包含计数

python - 如何从 boto3 cloudformation describe_stack API 中仅获取 OutputKey?

python - 使用 Python 按列组织数据文件的有效方法

python - 如何在同一目录中的另一个 python 脚本中调用 python 脚本?

python - 如何将对应于 'n' 的值列表排序到按 'n' 排序的大表中

python - 如何将我的 Dataframe 日期格式化为一种格式