Search code examples
pandasmulti-index

Align order of multiindex dataframe with the order of another multiindex df, pandas


I do have two multiindex dataframes, which contain the same multiindex levels. The only difference between them is the order in which the index levels are arranged.

Is there a way to reorder the levels of the multiindex from df1, so that they are the same as the ones from df2?

df1.index.names yields

FrozenList([u'Local code', u'Nature of holding', u'Issuer long name', u' Internal Issuer rating', u'holding type', u'Detailed Instrument'])

df2.index.names yields

FrozenList([u'Local code', u'Detailed Instrument', u'Nature of holding', u'Issuer long name', u'Internal Issuer rating', u'holding type'])

Is there a simple way to align the order of the index levels?


Solution

  • I think you need DataFrame.reorder_levels:

    df1 = df1.reorder_levels(df2.index.names)
    

    Sample:

    df1 = pd.DataFrame({'A':[7,2,3],
                       'B':[5,5,6],
                       'C':[4,8,9],
                       'D':[0,3,5],
                       'E':[8,3,6],
                       'F':[9,4,3]}).set_index(['A','B', 'C'])
    
    print (df1)
           D  E  F
    A B C         
    7 5 4  0  8  9
    2 5 8  3  3  4
    3 6 9  5  6  3
    
    df2 = pd.DataFrame({'A':[1,2,3],
                       'B':[4,5,6],
                       'C':[7,8,9],
                       'D':[1,3,5],
                       'E':[5,3,6],
                       'F':[7,4,3]}).set_index(['C','A', 'B'])
    
    print (df2)
           D  E  F
    C A B         
    7 1 4  1  5  7
    8 2 5  3  3  4
    9 3 6  5  6  3
    
    df1 = df1.reorder_levels(df2.index.names)
    print (df1)
           D  E  F
    C A B         
    4 7 5  0  8  9
    8 2 5  3  3  4
    9 3 6  5  6  3