Removing Duplicates
Duplicate rows creep in when a form is submitted twice, when two exports overlap, or when the same file is loaded twice. They silently inflate counts and totals, so finding and removing them is a standard cleaning step.
Finding duplicates
duplicated() returns a boolean Series: True for every row that is an exact copy of a row above it.
import pandas as pd
signups = pd.DataFrame({
"email": ["kim@ex.com", "lou@ex.com", "kim@ex.com", "max@ex.com", "lou@ex.com"],
"workshop": ["pottery", "yoga", "pottery", "yoga", "pottery"],
"seats": [1, 2, 1, 1, 2],
})
print(signups.duplicated())
print("Exact duplicates:", signups.duplicated().sum())0 False
1 False
2 True
3 False
4 False
dtype: bool
Exact duplicates: 1
Only row 2 is flagged: it matches row 0 in every column. Row 4 shares an email with row 1 but differs in the workshop, so it is not an exact duplicate.
Removing duplicates
drop_duplicates() returns a new DataFrame without the duplicate rows:
import pandas as pd
signups = pd.DataFrame({
"email": ["kim@ex.com", "lou@ex.com", "kim@ex.com", "max@ex.com", "lou@ex.com"],
"workshop": ["pottery", "yoga", "pottery", "yoga", "pottery"],
"seats": [1, 2, 1, 1, 2],
})
clean = signups.drop_duplicates()
print(clean)
print(clean.reset_index(drop=True)) email workshop seats
0 kim@ex.com pottery 1
1 lou@ex.com yoga 2
3 max@ex.com yoga 1
4 lou@ex.com pottery 2
email workshop seats
0 kim@ex.com pottery 1
1 lou@ex.com yoga 2
2 max@ex.com yoga 1
3 lou@ex.com pottery 2
The surviving rows keep their original index labels (0, 1, 3, 4). reset_index(drop=True) renumbers them from 0 if you prefer a tidy index.
Duplicates in some columns only
Often only certain columns define "the same record". If each email may sign up only once, check just that column with subset. The keep argument chooses which copy survives:
keep= |
Result |
|---|---|
"first" (default) |
keep the first occurrence |
"last" |
keep the last occurrence |
False |
drop every row that has a duplicate |
import pandas as pd
signups = pd.DataFrame({
"email": ["kim@ex.com", "lou@ex.com", "kim@ex.com", "max@ex.com", "lou@ex.com"],
"workshop": ["pottery", "yoga", "pottery", "yoga", "pottery"],
"seats": [1, 2, 1, 1, 2],
})
print(signups.drop_duplicates(subset=["email"]))
print(signups.drop_duplicates(subset=["email"], keep="last"))
print(signups[signups.duplicated(subset=["email"], keep=False)]) email workshop seats
0 kim@ex.com pottery 1
1 lou@ex.com yoga 2
3 max@ex.com yoga 1
email workshop seats
2 kim@ex.com pottery 1
3 max@ex.com yoga 1
4 lou@ex.com pottery 2
email workshop seats
0 kim@ex.com pottery 1
1 lou@ex.com yoga 2
2 kim@ex.com pottery 1
4 lou@ex.com pottery 2
The last line is a useful trick: duplicated(keep=False) marks all members of every duplicate group, so you can inspect them before deciding what to drop.
Keeping the newest record
A common real-world rule is "keep the most recent version of each record". Sort by time first, then keep the last row per key:
import pandas as pd
profiles = pd.DataFrame({
"user": ["ivy", "joe", "ivy", "joe", "ivy"],
"city": ["Leeds", "Cork", "York", "Cork", "Bath"],
"updated": pd.to_datetime(["2024-01-10", "2024-02-01", "2024-03-15",
"2024-01-05", "2024-02-20"]),
})
latest = (profiles.sort_values("updated")
.drop_duplicates(subset="user", keep="last")
.sort_values("user"))
print(latest) user city updated
2 ivy York 2024-03-15
1 joe Cork 2024-02-01
Ivy's newest row (March) says York, and Joe's newest (February) says Cork.
Duplicates in a Series and the index
The same methods exist on a Series, and index.duplicated() finds repeated row labels, which can cause surprises when you look rows up with loc:
import pandas as pd
tags = pd.Series(["red", "blue", "red", "green", "blue"])
print(tags.drop_duplicates().to_list())
print(tags.unique())
s = pd.Series([1, 2, 3], index=["a", "b", "a"])
print(s.index.duplicated())
print(s.loc["a"])['red', 'blue', 'green']
['red' 'blue' 'green']
[False False True]
a 1
a 3
dtype: int64
Because the label a appears twice, s.loc["a"] returns two values instead of one.
Test yourself
By default, which rows does df.duplicated() mark as True?
- Every row that has a copy anywhere
- Repeats of an earlier row (all but the first occurrence)
- The first occurrence of each repeated row
- Rows with missing values
How do you remove rows that repeat the same id, even if other columns differ?
- df.drop_duplicates("id")
- df.drop_duplicates(subset=["id"])
- df.unique("id")
- df.dropna(subset=["id"])
What does keep=False do in drop_duplicates?
- Keeps all rows
- Drops every row that belongs to a duplicate group
- Keeps only the duplicates
- Is not allowed