Introduction
Duplicate records occur when the same information appears more than once in a dataset. They can increase record counts and affect calculations, reports, and data analysis. Pandas provides functions such as duplicated() and drop_duplicates() to identify and remove repeated records. In this chapter, you will learn how to find and remove duplicates using Pandas Removing Duplicates.
What Are Duplicate Records in Pandas?
Duplicate records are rows that contain the same values as other rows in a DataFrame.
For example, an employee dataset may contain the same employee information more than once.
| Name | Department | Salary |
|---|---|---|
| Amit | IT | 35000 |
| Neha | HR | 40000 |
| Rahul | Sales | 32000 |
| Neha | HR | 40000 |
| Amit | IT | 35000 |
In this dataset:
- Amit’s record appears twice.
- Neha’s record appears twice.
- Rahul’s record appears only once.
These repeated records are called duplicate rows.
Creating a DataFrame with Duplicate Records
Let’s create a DataFrame containing duplicate employee records.
Example:
import pandas as pd
data = {
"Name": ["Amit", "Neha", "Rahul", "Neha", "Amit"],
"Department": ["IT", "HR", "Sales", "HR", "IT"],
"Salary": [35000, 40000, 32000, 40000, 35000]
}
df = pd.DataFrame(data)
print(df)
Output:
Name Department Salary
0 Amit IT 35000
1 Neha HR 40000
2 Rahul Sales 32000
3 Neha HR 40000
4 Amit IT 35000
Explanation: The DataFrame contains five rows, but some employee records are repeated. We will identify these duplicate records and remove them using Pandas.
Identifying Duplicate Records Using duplicated()
The duplicated() function checks whether rows are repeated in a DataFrame.
It returns:
Trueif a row is a duplicate.Falseif a row is not a duplicate.
Syntax:
df.duplicated()
Example:
print(df.duplicated())
Output:
0 False
1 False
2 False
3 True
4 True
dtype: bool
Explanation: Pandas compares each row with the rows above it. The first occurrence is marked False, while repeated occurrences are marked True.
Counting Duplicate Records Using sum()
You can combine duplicated() with sum() to count the total number of duplicate rows.
Example:
print(df.duplicated().sum())
Output:
2
Explanation: The result is 2 because the DataFrame contains two duplicate rows.
Displaying Only Duplicate Records
You can use the result of duplicated() as a filter to display only duplicate rows.
Example:
print(df[df.duplicated()])
Output:
Name Department Salary
3 Neha HR 40000
4 Amit IT 35000
Explanation: The condition df.duplicated() selects only rows marked as duplicates. The original first occurrences are not displayed.
Removing Duplicate Records Using drop_duplicates()
The drop_duplicates() function removes repeated rows from a DataFrame.
Syntax:
df.drop_duplicates()
Example:
new_df = df.drop_duplicates()
print(new_df)
Output:
Name Department Salary
0 Amit IT 35000
1 Neha HR 40000
2 Rahul Sales 32000
Explanation: The drop_duplicates() function removes repeated rows and keeps the first occurrence by default.
The original DataFrame remains unchanged because the cleaned result is stored in new_df.
Removing Duplicates Using inplace=True
You can use inplace=True to remove duplicate rows directly from the original DataFrame.
Example:
df.drop_duplicates(inplace=True)
print(df)
Output:
Name Department Salary
0 Amit IT 35000
1 Neha HR 40000
2 Rahul Sales 32000
Explanation: The inplace=True parameter modifies the original DataFrame instead of returning a separate cleaned DataFrame.
Keeping the Last Duplicate Record Using keep=”last”
By default, drop_duplicates() keeps the first occurrence of a duplicate row.
You can use keep="last" to keep the last occurrence instead.
Example:
new_df = df.drop_duplicates(keep="last")
print(new_df)
Output:
Name Department Salary
2 Rahul Sales 32000
3 Neha HR 40000
4 Amit IT 35000
Explanation:
keep="last"keeps the last occurrence of each duplicate row.- Earlier repeated occurrences are removed.
- The original row order is maintained among the remaining rows.
Note: If you are following this example independently, create the original DataFrame again before running it because the previous inplace=True example modifies df.
Removing All Duplicate Occurrences Using keep=False
You can use keep=False to remove every occurrence of a duplicated row.
Unlike the default behavior, this option does not keep either the first or last occurrence.
Example:
data = {
"Name": ["Amit", "Neha", "Rahul", "Neha", "Amit"],
"Department": ["IT", "HR", "Sales", "HR", "IT"],
"Salary": [35000, 40000, 32000, 40000, 35000]
}
df = pd.DataFrame(data)
new_df = df.drop_duplicates(keep=False)
print(new_df)
Output:
Name Department Salary
2 Rahul Sales 32000
Explanation: Amit and Neha each have duplicate records. Therefore, all their occurrences are removed. Only Rahul’s unique record remains.
Identifying Duplicates Based on Specific Columns
Sometimes, you may want to identify duplicate values based on only one column instead of comparing the complete rows.
The subset parameter allows you to specify which columns should be checked.
Example:
data = {
"Name": ["Amit", "Neha", "Rahul", "Amit"],
"Department": ["IT", "HR", "Sales", "Marketing"],
"Salary": [35000, 40000, 32000, 45000]
}
df = pd.DataFrame(data)
print(df.duplicated(subset=["Name"]))
Output:
0 False
1 False
2 False
3 True
dtype: bool
Explanation: Pandas checks only the Name column. Since Amit appears twice, the second occurrence is marked True, even though the Department and Salary values are different.
Removing Duplicates Based on Specific Columns
You can also remove duplicate records by checking only selected columns using subset.
Example:
new_df = df.drop_duplicates(subset=["Name"])
print(new_df)
Output:
Name Department Salary
0 Amit IT 35000
1 Neha HR 40000
2 Rahul Sales 32000
Explanation: Pandas checks only the Name column and keeps the first record for each name. The second Amit record is removed.
Important: Use this method only when each name is expected to identify a unique person. In real datasets, two different employees may have the same name. A unique employee ID is usually a safer way to identify records.
Student Task
Create a DataFrame named employees using the following data:
| Employee ID | Name | Department | Salary |
|---|---|---|---|
| E101 | Amit | IT | 35000 |
| E102 | Neha | HR | 40000 |
| E103 | Rahul | Sales | 32000 |
| E102 | Neha | HR | 40000 |
| E104 | Priya | IT | 45000 |
| E101 | Amit | IT | 35000 |
Your Tasks:
- Create a Pandas DataFrame using the given employee data.
- Identify duplicate rows using
duplicated(). - Count duplicate records using
duplicated().sum(). - Display only duplicate records.
- Remove duplicate records using
drop_duplicates(). - Remove duplicates using
inplace=True. - Use
keep="last"to keep the last occurrence. - Identify duplicates based only on the Employee ID column.
- Remove duplicates based on Employee ID using
subset. - Display the final cleaned DataFrame.
Key Takeaways
- Duplicate records are repeated rows in a dataset.
duplicated()identifies duplicate rows.duplicated().sum()counts duplicate rows.- Boolean filtering displays only duplicate records.
drop_duplicates()removes duplicate rows.keep="first"keeps the first occurrence by default.keep="last"keeps the last occurrence.keep=Falseremoves all occurrences of duplicated rows.subsetchecks duplicates using selected columns.inplace=Truemodifies the original DataFrame.
Frequently Asked Questions (FAQs)
1. What Is Pandas Removing Duplicates in Python?
Pandas Removing Duplicates is the process of identifying and removing repeated rows from a DataFrame. It helps maintain clean, accurate, and organized datasets for data analysis.
2. How to Remove Duplicates in Pandas DataFrame?
You can Remove Duplicates in Pandas using the drop_duplicates() function. It removes duplicate rows from a DataFrame while keeping the first occurrence by default.
df.drop_duplicates()
3. How to Find Duplicate Rows in Pandas?
You can Find Duplicate Rows in Pandas using the duplicated() function. It returns True for duplicate rows and False for unique rows.
df.duplicated()
4. What Is the Use of Pandas duplicated() Function?
The Pandas duplicated() function is used to identify duplicate rows in a DataFrame. It returns Boolean values that indicate whether each row is a duplicate based on the selected columns.
5. What Is the Difference Between duplicated() and drop_duplicates() in Pandas?
The duplicated() function identifies duplicate rows and returns True or False values, whereas drop_duplicates() removes duplicate rows from a DataFrame. Both functions are useful for handling duplicate data.
6. How to Remove Duplicate Rows Based on a Specific Column in Pandas?
You can remove duplicate rows based on a specific column by using the subset parameter with drop_duplicates().
df.drop_duplicates(subset=["Name"])
This removes rows containing repeated values in the Name column.
7. How to Count Pandas Duplicate Rows in a DataFrame?
You can count duplicate rows in Pandas using the duplicated().sum() expression. It returns the total number of duplicate rows present in a DataFrame.
df.duplicated().sum()
8. Why Is Removing Duplicate Data Important in Pandas?
Removing duplicate data is important because repeated records can affect calculations, reports, and data analysis results. Pandas Removing Duplicates helps improve data accuracy and maintain a clean dataset.
9. How to Find Duplicate Rows in Pandas Using duplicated()?
You can Find Duplicate Rows in Pandas using the duplicated() function. It checks Pandas Duplicate Rows and returns True for repeated records and False for unique records.
df[df.duplicated()]
10. How Does Pandas duplicated() Identify Pandas Duplicate Rows?
The Pandas duplicated() function identifies Pandas Duplicate Rows by comparing row values in a DataFrame. It marks repeated rows as True while keeping the first occurrence as False by default.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
