0

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.

1 Answer 1

2

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]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.