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

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

问题描述

我正在尝试仅使用多索引DataFrame中的一个索引来创建新的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
`

基本上我想删除多索引的所有其他索引,而不是第一个 。有没有一种简单的方法可以做到这一点?

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天全站免登陆