How to merge two dataframe horizontally and arrange the columns according to our own preference?

Viewed 28

I want to merge two dataframe horizontally based on rank column also rearrange these columns according to our own preference

This is my first dataframe

df_pa       
Rank    Name_pa    Country_pa
1       A          US
2       B          US
3       C          UK
4       D          MA
5       E          AU

And this is my second dataframe

df_ca       
Rank    Name_ca    Country_ca
1       F          CA
2       G          PA
3       H          US
4       I          BR
5       J          CH

Can anyone please tell me how can we merge that two dataframe horizontally based on rank column also place these column according to our own preference

This is my expectation.

df              
Country_ca    Name_ca    Rank    Name_pa    Country_pa
CA            F          1       A          US
PA            G          2       B          US
US            H          3       C          UK
BR            I          4       D          MA
CH            J          5       E          AU
1 Answers

Swap order of all columns by DataFrame.iloc and then use DataFrame.merge:

df_ca.iloc[:, ::-1].merge(df_pa, on='Rank')

Or use custom ordering by list:

df_ca[['Country_ca','Name_ca','Rank']].merge(df_pa, on='Rank')
Related