Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

python - Select only one index of multiindex 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"]

and:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

or use the level's integer value:

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

All other levels of the MultiIndex would disappear here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...