Intersection of two dataframe in Pandas – Python

Intersection of Two data frames in Pandas can be easily calculated by using the pre-defined function merge(). This function takes both the data frames as argument and returns the intersection between them.

Syntax:

pd.merge(df1, df2, how)

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

import pandas as pd
  
# Creating Data frames
df1 = {'A': [1, 2, 3, 4],
         'B': ['abc', 'def', 'efg', 'ghi']} 
df2 = {'A': [1, 2, 3, 4 ],
         'B': ['Geeks', 'For', 'efg', 'ghi'],
         'C':['Nikhil', 'Rishabh', 'Rahul', 'Shubham']} 
           
d1 = pd.DataFrame(df1)
d2 = pd.DataFrame(df2) 
  
# Calling merge() function
int_df = pd.merge(d1, d2, how ='inner', on =['A', 'B'])
print(int_df)

chevron_right


Output:

   A    B        C
0  3  efg    Rahul
1  4  ghi  Shubham

Example 2:



filter_none

edit
close

play_arrow

link
brightness_4
code

import pandas as pd
  
# Creating Data frames
df1 = {'A': [1, 2, 3, 4],
         'B': ['Geeks', 'For', 'efg', 'ghi']} 
df2 = {'A': [1, 2, 3, 4 ],
         'B': ['Geeks', 'For', 'abc', 'cde'],
         'C':['Nikhil', 'Rishabh', 'Rahul', 'Shubham']} 
           
d1 = pd.DataFrame(df1)
d2 = pd.DataFrame(df2) 
  
# Calling merge() function
int_df = pd.merge(d1, d2, how='inner', on=['A', 'B'])
print(int_df)

chevron_right


Output:

   A      B        C
0  1  Geeks   Nikhil
1  2    For  Rishabh

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.