仅选择多索引 DataFrame 的一个索引 [英] Select only one index of multiindex DataFrame

查看:35
本文介绍了仅选择多索引 DataFrame 的一个索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅使用多索引数据帧中的一个索引来创建新数据帧.

I am trying to create a new DataFrame using only one index from a multi-indexed DataFrame.

                   A         B         C
first second                              
bar   one     0.895717  0.410835 -1.413681
      two     0.805244  0.813850  1.607920
baz   one    -1.206412  0.132003  1.024180
      two     2.565646 -0.827317  0.569605
foo   one     1.431256 -0.076467  0.875906
      two     1.340309 -1.187678 -2.211372
qux   one    -1.170299  1.130127  0.974466
      two    -0.226169 -1.436737 -2.006747

理想情况下,我想要这样的东西:

Ideally, I would like something like this:

In: df.ix[level="first"]

和:

Out:

               A         B         C
first                               
bar        0.895717  0.410835 -1.413681
           0.805244  0.813850  1.607920
baz       -1.206412  0.132003  1.024180
           2.565646 -0.827317  0.569605
foo        1.431256 -0.076467  0.875906
           1.340309 -1.187678 -2.211372
qux       -1.170299  1.130127  0.974466
          -0.226169 -1.436737 -2.006747
`

基本上我想删除除级别 first 以外的多索引的所有其他索引.有没有简单的方法可以做到这一点?

Essentially I want to drop all the other indexes of the multi-index other than level first. Is there an easy way to do this?

推荐答案

一种方法可能是简单地将 df.index 重新绑定到所需的 MultiIndex 级别.您可以通过指定要保留的标签名称来执行此操作:

One way could be to simply rebind df.index to the desired level of the MultiIndex. You can do this by specifying the label name you want to keep:

df.index = df.index.get_level_values('first')

或使用级别的整数值:

df.index = df.index.get_level_values(0)

MultiIndex 的所有其他级别都将在此处消失.

All other levels of the MultiIndex would disappear here.

这篇关于仅选择多索引 DataFrame 的一个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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