Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading