Sort Multi-index pandas dataframe based on specific indexes
<p>I have the following dataframe:</p>

<pre><code> 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
</code></pre>

<p>what I want is:</p>

<pre><code> 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 
</code></pre>

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

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

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

new_idx = df_sort.index    --&gt;    new_idx = (['ii','kk','jj'])
</code></pre>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a>:</p>

<pre><code>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  
</code></pre>

python sorting pandas dataframe multi-index