How to find the common rows between two DataFrames with merge()
Overview
A DataFrame is a two-dimensional data structure in which data is aligned in rows and columns. In this Answer, we'll learn how to find the common rows between two DataFrames using the `merge()` function in Python pandas.
Syntax
df1.merge(df2, how = 'inner' ,indicator=False)
In the syntax above, df1 and df2 are two DataFrames.
We pass inner as a value to the how parameter to get the common rows between two DataFrames. This operation is similar to InnerJoin in SQL.
Example
import pandas as pd#data frame 1classA = pd.DataFrame({"Student": ['John', 'Lexi', 'Augustin', 'Jane', 'Kate'],"Age": [18, 17, 19, 17, 18]})#data frame 2classB = pd.DataFrame({"Student": ['John', 'Lexi', 'Bob', 'karl', 'Kate', 'Jane'],"Age": [18, 17, 16, 19, 18, 20]})#get uncommon rowsprint(classA.merge(classB, how = 'inner' ,indicator=False))
Explanation
In the above code snippet,
- Line 1: We import the
pandasmodule, which contains methods to create DataFrames and modify them. - Lines 4–8 and 13–19: We create two DataFrames that represent two classes of students. These data frames contain students' names and their ages.
- Line 21: We get the common students between the two classes
classAandclassBby merging both DataFrames using themerge()method and passinginneras the value to thehowparameter.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved