3

I have a multi-indexed dataframe with names attached to the column levels. The data table looks something like this: (df1)

                        TIME                    
         TMC    111N1   111P2   111N3   111P4   
DATE    EPOCH                   
          0     143     113      103    NaN 
          1     183     NaN      NaN    NaN 
          2     NaN     NaN      NaN    NaN 
          3     143     NaN      NaN    NaN 

I'd like to shuffle the columns around so that they match the order specified by the rows index of a reference dataframe (df2):

        A1  A2  A3    A4    A5
 Name                                                                               
 111N3  PA  PL  er  0.75543 35
 111P4  PA  PL  er  0.09413 35
 111N1  PA  PL  er  4.21557 35
 111P2  PA  PL  er  1.31989 35

i.e. the result should be (df3):

                        TIME                    
         TMC    111N3   111P4   111N1   111P2   
DATE    EPOCH                   
          0     103     NaN      143    113 
          1     NaN     NaN      183    NaN 
          2     NaN     NaN      NaN    NaN 
          3     NaN     NaN      143    NaN 
GB7
  • 73
  • 1
  • 6

1 Answers1

3

reindex_axis will use the labels from the other dataframe and let you specific the axis to reindex and also a particular level:

df1.reindex_axis(df2.index, axis=1, level=1)
Zeugma
  • 31,231
  • 9
  • 69
  • 81
  • Thanks! It worked. i just made a slight change to: 'df1.reindex_axis(df2.index, axis=1, level=1)' – GB7 Nov 15 '16 at 06:14
  • 1
    This answer should be highly viewed. Superb ! Here are some bad answers for the same problem: https://stackoverflow.com/questions/11194610/how-can-i-reorder-multi-indexed-dataframe-columns-at-a-specific-level https://stackoverflow.com/questions/52046075/how-to-re-order-the-multi-index-columns-using-pandas – bonney Feb 06 '20 at 03:51
  • 1
    reindex_axis is deprecated since version 0.21.0: Use reindex instead. – Ferro Jul 04 '20 at 17:55