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

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)

Leave a Comment

deneme bonusu veren sitelerbahis casinomakrobetceltabetpinbahispolobetpolobet girişpinbahis girişmakrobet girişpulibet girişmobilbahis girişkolaybet giriş