Sub topic 9
Finding duplicate rows with duplicated
This chapter assumes you can create a DataFrame, select columns, and use boolean masks to filter rows. By the end you will be able to flag repeated rows, choose which copy counts as the original, and count the duplicates.
What duplicated returns
DataFrame.duplicated() returns a boolean Series with one entry per row. An entry is True when that row repeats an earlier row. The index matches the DataFrame, so you can use the result as a mask.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
is_dup = df.duplicated(subset=["city", "plan"])
print(is_dup.tolist()) # [False, False, True, False, True, False, False]
print(is_dup.sum()) # 2
print(df[is_dup]) # rows 2 and 4Rows 2 and 4 are flagged because each repeats an earlier row on both columns. Row 5 is not flagged. It has the same city as rows 0 and 2, but its plan differs.
Choosing the columns with subset
Without subset, all columns must match. With subset, only the listed columns are compared. Pass a list, even for one column.
print(df.duplicated().sum()) # 2, all columns compared
print(df.duplicated(subset=["city"]).sum()) # 3, rows 2, 4 and 5 repeat a cityComparing on fewer columns produces more duplicates. Choose the subset that defines what "the same record" means in your data, such as a customer ID rather than every field.
Choosing which copy counts with keep
The keep argument controls which rows are marked True.
| keep | Effect |
|---|---|
| `"first"` (default) | Later copies are `True`; the first occurrence is `False` |
| `"last"` | Earlier copies are `True`; the last occurrence is `False` |
| `False` | Every row that belongs to a duplicated group is `True` |
cols = ["city", "plan"]
print(df.duplicated(subset=cols, keep="last").tolist())
# [True, True, False, False, False, False, False]
all_copies = df[df.duplicated(subset=cols, keep=False)]
print(all_copies.index.tolist()) # [0, 1, 2, 4]Use keep=False when you want to inspect every copy of a repeated record, for example to compare conflicting values before deciding what to delete.
Missing values count as equal
duplicated treats missing values as equal to each other. If two rows both have None in city and match elsewhere, the second one is flagged. This differs from ordinary comparison, where NaN == NaN is False. If missing values should not count as matches, fill or filter them first.
Common mistakes
- Passing a string to
subsetthat is not a column name raises aKeyError. - Reading
Falseas "unique". With the defaultkeep, the first copy of a repeated record is alsoFalse. Usekeep=Falseto find all rows that have a twin. - Forgetting that
duplicatedcompares exact values."Oslo"and"oslo "are different, so clean case and whitespace first, for example withdf["city"].str.strip().str.lower().
Exercise
Using the DataFrame above, write one line that returns only the rows whose city appears more than once, including the first occurrence of each. How many rows does it return?
Show answer
df[df.duplicated(subset=["city"], keep=False)] returns 5 rows. Oslo appears three times (rows 0, 2, 5) and Rome twice (rows 1, 4). Paris appears once and the missing value appears once, so both are excluded.