Replicate pd.concat using pd.merge

Viewed 54

Is it possible to replicate the following using pd.merge

a = pd.DataFrame(dict(x=[1,2], y=[5,5]))
b = pd.DataFrame(dict(x=[7,7], y=[12,13]))
pd.concat([a,b],axis=1)

which outputs

   x  y  x   y
0  1  5  7  12
1  2  5  7  13

As this would enable me to add suffixes to the column names.

I expected the following to work:

pd.merge(a, b, how = 'outer',)

but this returns:

   x   y
0  1   5
1  2   5
2  7  12
3  7  13

i would like the output to be:

   x_l  y_l  x_r   y_r
0  1    5    7    12  
1  2    5    7    13  
2 Answers

You can use df.join too:

a.join(b,lsuffix='_l',rsuffix='_r')

   x_l  y_l  x_r  y_r
0    1    5    7   12
1    2    5    7   13

IIUC fix your concat by adding the keys

s=pd.concat([a,b], axis=1,keys=['l_','r_'])
s.columns=s.columns.map(''.join)
s
   l_x  l_y  r_x  r_y
0    1    5    7   12
1    2    5    7   13
Related