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

Merged Pandas dataframe columns side by side

If I merge on two dataframes as shown

df1=pd.DataFrame({"Name": ["Alex","Ben","Cat","Dog"],'A':[1,2,3,3],'B':[2,3,4,4]})
df2=pd.DataFrame({"Name": ["Alex","Ben","Cat","Dog"],'A':[2,3,4,4],'B':[1,2,3,3]})

df_merged = pd.merge(df1,df2, on = "Name", suffixes= ["L","R"])

this is what my merged dataframe df_merged is like

Name    AL  BL  AR  BR
0   Alex 1  1   2   2   
1   Ben  2  3   3   2
2   Cat  3  4   4   3
3   Dog  3  4   4   3

But is there a way to get df_merged to look like

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

Name    AL AR BL BR
0   Alex 1  2  1  2 
1   Ben  2  3  3  2
2   Cat  3  4  4  3
3   Dog  3  4  4  3

where the columns of the dataframes are next to one other.

This is just an interest for cosmetic reasons rather than anything else. I couldn’t find an example for it anywhere.

>Solution :

You need change order of columns, here is dynamic approach:

#get all columns names in both df, removed Name used for key in merge
same = df1.columns.intersection(df2.columns, sort=False).difference(['Name'])

#generate columns in order
cols = [f'{a}{b}' for a in same for b in ['L','R']]

#get different like `cols` from merged df and add cols in order
order = df_merged.columns.difference(cols, sort=False).union(cols, sort=False)

#changed order by list
df = df_merged[order]
print (df)
   Name  AL  AR  BL  BR
0  Alex   1   2   2   1
1   Ben   2   3   3   2
2   Cat   3   4   4   3
3   Dog   3   4   4   3

Manually approach:

df = df_merged[['Name', 'AL', 'AR', 'BL', 'BR']]
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