Home > Mobile >  Reorder the columns based on another DataFrame without manually type the column names
Reorder the columns based on another DataFrame without manually type the column names

Time:12-05

I have two DataFrames df1 and df2 which contain both the same columns but in a different order. Is there an efficient way to reorder the columns of df2 based on the order of the columns of df1 without manually specifying the column names?

This would be a simple example:

df1
    Date        ID1 ID2 ID3 ID4 ID5
0   2021-01-01  0   1   0   1   0
1   2021-01-02  0   0   1   0   0
2   2021-01-03  1   0   1   1   0

df2
    Date        ID4 ID2 ID1 ID3 ID5
0   2021-01-01  1   1   0   0   0
1   2021-01-02  0   0   0   1   0
2   2021-01-03  1   0   1   1   0

For reproducibility:

df1 = pd.DataFrame({
    'Date':['2021-01-01', '2021-01-02', '2021-01-03'],
    'ID1':[0,0,1], 
    'ID2':[1,0,0],
    'ID3':[0,1,1], 
    'ID4':[1,0,1], 
    'ID5':[0,0,0]})

df2 = pd.DataFrame({
    'Date':['2021-01-01', '2021-01-02', '2021-01-03'],
    'ID4':[1,0,1],
    'ID2':[1,0,0],
    'ID1':[0,0,1], 
    'ID3':[0,1,1],     
    'ID5':[0,0,0]})

Thanks a lot.

CodePudding user response:

You can reorder the columns by passing a column list -

In your case, to use the columns on the first dataframe on the second df2[df1.columns]

  • Related