31

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?

1 Answer 1

45

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)
2
  • Nice, can chain with the alternative solution
    – Tunn
    Jan 9, 2018 at 16:33
  • @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.
    – K.S
    May 7, 2019 at 10:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.