Python Pandas – Find the common rows between two Data Frames


To find the common rows between two DataFrames, use the merge() method. Let us first create DataFrame1 with two columns −

dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90] }
)

Create DataFrame2 with two columns −

dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 250, 150, 80, 130, 90]
   }
)

To find the common rows −

dataFrame1.merge(dataFrame2, how = 'inner' ,indicator=False)

Example

Following is the code −

import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90] }
)

print"DataFrame1 ...\n",dataFrame1

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 250, 150, 80, 130, 90]
   }
)

print"\nDataFrame2 ...\n",dataFrame2

# check for equality
print"\nAre both the DataFrames equal? ",dataFrame1.equals(dataFrame2)

# finding common rows between two DataFrames
resData = dataFrame1.merge(dataFrame2, how = 'inner' ,indicator=False)
print"\nCommon rows between two DataFrames...\n",resData

Output

This will produce the following output −

DataFrame1 ...
       Car   Units
0      BMW    100
1    Lexus    150
2     Audi    110
3    Tesla     80
4  Bentley    110
5   Jaguar     90

DataFrame2 ...
       Car   Units
0      BMW    100
1    Lexus    250
2     Audi    150
3  Mustang     80
4  Bentley    130
5   Jaguar     90

Are both the DataFrames equal? False

Common rows between two DataFrames...
      Car   Units
0     BMW    100
1  Jaguar     90

Updated on: 15-Sep-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements