tryingtocode101
tryingtocode101

Reputation: 89

Pandas - merge two dataframes based off of intersection of columns

I am new to dataframe manipulation. I've been playing around with df.merge, df.join, pd.concat and I've been getting frequent errors while being unable to merge without duplicates.

I have two representative dataframes I want to merge.

df1 = pd.DataFrame({'1990' : 1, '1991': 2, '1992': 3}, index = ['a','b','c'])

enter image description here

df2 = pd.DataFrame({'1989':0,'1990' : 1, '1991': 2, '1992': 3, '1993': 4}, index = ['d'])

enter image description here

I want to merge them by the intersection of the columns of the two dataframes while adding the row at the same time. Is there a way to use a dataframe method to do this?

The final product should look like:

enter image description here

Upvotes: 2

Views: 1359

Answers (1)

jezrael
jezrael

Reputation: 862406

Use concat with inner join:

df = pd.concat([df1, df2], join='inner')
print (df)
   1990  1991  1992
a     1     2     3
b     1     2     3
c     1     2     3
d     1     2     3

Upvotes: 1

Related Questions