How to re-order the columns based on another dataframe with the same columns but different order

11,988

Try this:

df2 = df2[df1.columns]

Demo:

In [1]: df1 = pd.DataFrame(np.random.randint(0, 10, (5,4)), columns=list('abcd'))

In [2]: df2 = pd.DataFrame(np.random.randint(0, 10, (5,4)), columns=list('badc'))

In [3]: df1
Out[3]:
   a  b  c  d
0  8  3  9  6
1  0  6  4  7
2  7  2  0  7
3  0  5  1  8
4  6  2  5  4

In [4]: df2
Out[4]:
   b  a  d  c
0  3  8  0  4
1  7  7  4  2
2  2  7  3  8
3  2  4  9  6
4  3  4  7  1

In [5]: df2 = df2[df1.columns]

In [6]: df2
Out[6]:
   a  b  c  d
0  8  3  4  0
1  7  7  2  4
2  7  2  8  3
3  4  2  6  9
4  4  3  1  7

Alternative solution:

df2 = df2.reindex_axis(df1.columns, axis=1)

Note: Pandas reindex_axis is deprecated since version 0.21.0: Use reindex instead.

df2 = df2.reindex(df1.columns, axis=1)
Share:
11,988

Related videos on Youtube

renakre
Author by

renakre

a researcher..

Updated on September 16, 2022

Comments

  • renakre
    renakre over 1 year

    I wonder if there is a handy method to order the columns of a dataframe based on another one that has the same columns but with different order. Or, do I have to make a loop to achieve this?

  • Tunn
    Tunn over 6 years
    Nice, can chain with the alternative solution
  • K.S
    K.S almost 5 years
    @MaxU I have a similar problem, Have to rearrange the dataframe according to list but the names are diffferent. Can it be achieved by this way.