Chaymae Ahmed
Chaymae Ahmed

Reputation: 371

Merging two dataframes on the intersection of a given column

I want to merge the following two dataframes on their intersection on column 'Name'.

suppose dataframe 1 is:

     Name subject_id  Marks_scored
0   Billy       sub1            98
1     Amy       sub2            90
2    Bran       sub4            87
3   Alice       sub6            69
4  Ayoung       sub5            78

and dataframe 2 is:

    Name subject_id  Marks_scored
0  Billy       sub2            89
1  Brian       sub4            80
2   Bran       sub3            79
3  Bryce       sub6            97
4  Betty       sub5            88

I just want the output to be:

    Name subject_id  Marks_scored
0  Billy       sub1            98
1   Bran       sub4            87
2  Billy       sub2            89
3   Bran       sub3            79

Upvotes: 4

Views: 7928

Answers (2)

Marcos Marques
Marcos Marques

Reputation: 85

pd.concat([df1, df2], axis=1, join='inner')

OR

pd.merge(df1, df2, on='subject_id', how='inner')

Upvotes: 5

Scott Boston
Scott Boston

Reputation: 153460

Try using pd.concat then duplicated and boolean indexing:

df_out = pd.concat([df1,df2])
df_out[df_out.duplicated('Name', keep=False)]

Output:

    Name subject_id  Marks_scored
0  Billy       sub1            98
2   Bran       sub4            87
0  Billy       sub2            89
2   Bran       sub3            79

Upvotes: 1

Related Questions