Python Pandas - Finding the uncommon rows between two DataFrames


To find the uncommon rows between two DataFrames, use the concat() method. Let us first import the required library with alias −

import pandas as pd

Create DataFrame1 with two columns −

dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Reg_Price": [1000, 1500, 1100, 800, 1100, 900]
   }
)

Create DataFrame2 with two columns −

dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Reg_Price": [1000, 1300, 1000, 800, 1100, 800]
   }
)

Finding uncommon rows between two DataFrames and concatenate the result −

print"\nUncommon rows between two DataFrames...\n",pd.concat([dataFrame1,dataFrame2]).drop_duplicates(keep=False)

Example

Following is the code −

import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Reg_Price": [1000, 1500, 1100, 800, 1100, 900]
   }
)

print"DataFrame1 ...\n",dataFrame1

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Reg_Price": [1000, 1300, 1000, 800, 1100, 800]
   }
)

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

# finding uncommon rows between two DataFrames and concat the result
print"\nUncommon rows between two DataFrames...\n",pd.concat([dataFrame1,dataFrame2]).drop_duplicates(keep=False)


Output

This will produce the following output −

DataFrame1 ...
       Car   Reg_Price
0      BMW        1000
1    Lexus        1500
2     Audi        1100
3    Tesla         800
4  Bentley        1100
5   Jaguar         900

DataFrame2 ...
       Car   Reg_Price
0      BMW        1000
1    Lexus        1300
2     Audi        1000
3    Tesla         800
4  Bentley        1100
5   Jaguar         800

Uncommon rows between two DataFrames...
      Car   Reg_Price
1   Lexus        1500
2    Audi        1100
5  Jaguar         900
1   Lexus        1300
2    Audi        1000
5  Jaguar         800

Updated on: 15-Sep-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements