Loading content...
Loading content...
Master professional duplicate record detection, evaluation, and deduplication. Distinguish true duplicate records from innocent repeated values, inspect duplicate rows with boolean indexing, control retention using keep, and enforce business keys with subset.
The analytical problem of repeated rows in business datasets
Consider this customer database extract:
| Index | CustomerID | Name | City | Status |
|---|---|---|---|---|
| 0 | 101 | Amit | Mumbai | Original |
| 1 | 102 | Priya | Delhi | Original |
| 2 | 101 | Amit | Mumbai | Duplicate |
| 3 | 103 | Rahul | Pune | Original |
Row 2 is an exact duplicate of Row 0. Duplicate records frequently infiltrate datasets due to:
Detecting duplicate rows and calculating total counts
Pandas provides df.duplicated() to detect duplicate records. It returns a boolean Series:
First occurrence of a unique row.
Subsequent repeated duplicate.
Total number of duplicate rows.
Isolates duplicate rows for review.
df[df.duplicated()] filters the table to show only the rows marked as True, letting you inspect the duplicates before deleting them!Inspect duplicate masks and filter duplicate records
Given the customer table below, practice identifying, counting, and viewing duplicate rows:
A critical distinction every junior analyst must grasp
"Mumbai" appears 3 times. Does this mean we have 3 duplicate rows? Absolutely not! Amit (101) lives in Mumbai, and Neha (104) also lives in Mumbai. They are two completely distinct human beings who happen to reside in the same city!Safely generating clean, deduplicated DataFrames
Once duplicates are identified and confirmed, use drop_duplicates() to remove them:
# Generate a new DataFrame with duplicate rows removed df_clean = df.drop_duplicates()
df_clean = df.drop_duplicates()). Avoid modifying datasets in-place so you can trace your cleaning steps.Controlling which occurrence of a duplicate group survives
When identical records exist, which one should be kept? The keep argument gives you control:
df.drop_duplicates(keep="first")Keeps the first occurrence encountered. Marks and drops all subsequent occurrences.
df.drop_duplicates(keep="last")Keeps the last occurrence encountered. Marks and drops all earlier occurrences.
df.drop_duplicates(keep=False)Drops all occurrences in the duplicate group. Retains only truly unique records.
Execute each retention strategy and compare the output
Enforcing primary key uniqueness when secondary columns differ
In real enterprise data, two records representing the exact same customer may have different secondary fields (e.g. an address update):
| CustomerID | Name | City | Analysis |
|---|---|---|---|
| 101 | Amit | Mumbai | Older address record |
| 101 | Amit | Pune | Newer address record |
If you run df.drop_duplicates() without parameters, neither row is dropped because the cities differ! To tell Pandas that CustomerID defines a unique entity, use subset:
# Deduplicate by primary key only df.drop_duplicates(subset=["CustomerID"]) # Deduplicate by combined business keys df.drop_duplicates(subset=["CustomerID", "Email"])
Observe the difference between full-row and key-based deduplication
The myth of "keep='last' always means newest"
keep="last" does NOT magically know which record is the newest! It merely looks at row position in the DataFrame. If your DataFrame is NOT sorted by timestamp or update date, keep="last" could discard your newest update and preserve stale data!df = df.sort_values("UpdatedAt")df_clean = df.drop_duplicates(subset=["CustomerID"], keep="last")A disciplined framework for data cleaning
df.duplicated().sum()
df[df.duplicated(keep=False)]
Identify subset columns
keep="first" or "last"
drop_duplicates(subset=...)
sum() == 0
Diagnosing customer CRM records
Consider this realistic marketing CRM export:
| CustomerID | Name | City | |
|---|---|---|---|
| 101 | Amit | amit@example.com | Mumbai |
| 102 | Priya | priya@example.com | Delhi |
| 103 | Rahul | rahul@example.com | Pune |
| 101 | Amit | amit@example.com | Mumbai |
| 104 | Neha | neha@example.com | Mumbai |
| 102 | Priya | priya@example.com | Delhi |
df.drop_duplicates(subset=["CustomerID"], keep="first") cleans the dataset safely!Audit, clean, and verify customer identities
In the code editor below, detect duplicates using the customer key "CustomerID", remove them keeping the first record, and verify that .duplicated().sum() equals 0:
Pitfalls encountered when deduplicating records
Just because 50 customers live in Mumbai does not mean they are duplicates. Always distinguish between repeated attributes and duplicate entity identities.
If records have minor timestamp or address discrepancies, drop_duplicates() without subset will fail to catch duplicates of the same customer!
keep="last" only preserves the newest record if your DataFrame was sorted by timestamp beforehand.
Always run df.duplicated(subset=...).sum() immediately after deduplication to confirm that duplicate counts are down to zero.
Test your understanding of duplicate detection and deduplication
Validate your understanding of duplicated(), drop_duplicates(), subset, and keep strategies.
Why does a repeated value in one column (e.g. City="Mumbai") NOT automatically mean the entire row is a duplicate?
What you can now do with Python Deduplication
df.duplicated().sum().df[df.duplicated()].keep="first", "last", and False.subset parameter.