How to match two data frames with different column names in pandas? - python

df1 = pd.DataFrame({'a':[1,2,3],'x':[4,5,6],'y':[7,8,9]}) df2 = pd.DataFrame({'b':[10,11,12],'x':[13,14,15],'y':[16,17,18]}) 

I am trying to combine two data frames using the keys from df1 . I think pd.merge needs to be used for this, but I can tell pandas to place the values ​​in column b df2 in column a df1 . This is the result that I am trying to achieve:

  axy 0 1 4 7 1 2 5 8 2 3 6 9 3 10 13 16 4 11 14 17 5 12 15 18 
+8
source share
1 answer

Just use the concat and rename column for df2 so that it aligns:

 In [92]: pd.concat([df1,df2.rename(columns={'b':'a'})], ignore_index=True) Out[92]: axy 0 1 4 7 1 2 5 8 2 3 6 9 3 10 13 16 4 11 14 17 5 12 15 18 

You can use merge same way, but you will need to rename the column as above:

 In [103]: df1.merge(df2.rename(columns={'b':'a'}),how='outer') Out[103]: axy 0 1 4 7 1 2 5 8 2 3 6 9 3 10 13 16 4 11 14 17 5 12 15 18 
+12
source

All Articles