1

I have the following dataframe:

 x                                        y

 a            b            c              a          b          c

 kk  ii  jj   kk  jj  ii   kk  jj  ii    ii  jj kk  jj kk ii   kk ii jj

 1  .1  .01  2   .5  .2  .4   .6  .01  .3   .5  .7  1.  1.  2  .3  .2 .01 .4  

 2  .5  .01  2    3  .1   4   .3  .1  .01  .02  2   1   5  .7 .3   2  4.5  2.

 3  .01  .1  .4   .1 .5  .2    3  .6   1    3  .2   3  .2   1  1  .5  .2   1

what I want is:

 x                                        y

 a            b            c              a          b          c

 ii  kk  jj   ii  kk  jj   ii  kk  jj    ii  kk  jj  ii  kk  jj   ii  kk  jj

 1  .01  .1  2   .4  .5  .2   .3  .6  .01   .5   1   .7  .3  2  1.   0.01 .2  .4

 2  0.1  .5  2    4   3  .1   .01 .3  .1   .02   1   2   .3  7  5     4.5  2  2

 3  .1  .01 .4   .2  .1  .5    1  3  .6     3    3  .2    1  1  .2    .2  .5  1 

In fact, the aim is to sort the whole dataframe based on df['1']['x']['a'].

I got the new index of sorting, but I do not know how can I reindex df based on new_idx?

df_sort = df.loc['1']['x']['a'].sort_values(axis=0) 

new_idx = df_sort.index    -->    new_idx = (['ii','kk','jj'])

1 Answer 1

2

You can use reindex:

df = df.reindex(columns=['ii','kk','jj'], level=2)
print (df)
      x                                                y                      \
      a               b               c                a              b        
     ii    kk   jj   ii   kk   jj    ii   kk    jj    ii   kk   jj   ii   kk   
1  0.01  0.10  2.0  0.4  0.5  0.2  0.30  0.6  0.01  0.50  1.0  0.7  0.3  2.0   
2  0.01  0.50  2.0  4.0  3.0  0.1  0.01  0.3  0.10  0.02  1.0  2.0  0.3  0.7   
3  0.10  0.01  0.4  0.2  0.1  0.5  1.00  3.0  0.60  3.00  3.0  0.2  1.0  1.0   


           c            
    jj    ii   kk   jj  
1  1.0  0.01  0.2  0.4  
2  5.0  4.50  2.0  2.0  
3  0.2  0.20  0.5  1.0  
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.