如何访问 pandas 数据框中的多级索引? [英] How to access multi-level index in pandas data frame?

查看:94
本文介绍了如何访问 pandas 数据框中的多级索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用相同的索引调用那些行.

I would like to call those row with same index.

这是示例数据帧,

arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]

df = pd.DataFrame(np.random.randn(8, 4), index=arrays)

In [16]: df
Out[16]: 
                0         1         2         3
bar one -0.424972  0.567020  0.276232 -1.087401
    two -0.673690  0.113648 -1.478427  0.524988
baz one  0.404705  0.577046 -1.715002 -1.039268
    two -0.370647 -1.157892 -1.344312  0.844885
foo one  1.075770 -0.109050  1.643563 -1.469388
    two  0.357021 -0.674600 -1.776904 -0.968914
qux one -1.294524  0.413738  0.276662 -0.472035
    two -0.013960 -0.362543 -0.006154 -0.923061

我想选择

                0         1         2         3
bar one -0.424972  0.567020  0.276232 -1.087401
baz one  0.404705  0.577046 -1.715002 -1.039268
foo one  1.075770 -0.109050  1.643563 -1.469388
qux one -1.294524  0.413738  0.276662 -0.472035

甚至是这种格式

            0         1         2         3
one -0.424972  0.567020  0.276232 -1.087401
one  0.404705  0.577046 -1.715002 -1.039268
one  1.075770 -0.109050  1.643563 -1.469388
one -1.294524  0.413738  0.276662 -0.472035

我尝试了df['bar','one],但它不起作用.我现在确定应该如何访问多级索引.

I have tried df['bar','one] and it's not working. I am now sure how should I access the multi-level index.

推荐答案

您可以使用MultiIndex切片(使用slice(None)代替冒号):

You can use MultiIndex slicing (use slice(None) instead of colon):

df = df.loc[(slice(None), 'one'), :]

结果:

                0         1         2         3
bar one -0.424972  0.567020  0.276232 -1.087401
baz one  0.404705  0.577046 -1.715002 -1.039268
foo one  1.075770 -0.109050  1.643563 -1.469388
qux one -1.294524  0.413738  0.276662 -0.472035

最后,您可以删除第一个索引列:

Finally you can drop the first index column:

df.index = df.index.droplevel(0)

结果:

            0         1         2         3
one -0.424972  0.567020  0.276232 -1.087401
one  0.404705  0.577046 -1.715002 -1.039268
one  1.075770 -0.109050  1.643563 -1.469388
one -1.294524  0.413738  0.276662 -0.472035

这篇关于如何访问 pandas 数据框中的多级索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆