Sub topic 8
Finding duplicates with duplicated()
This chapter assumes you can build a DataFrame, select columns by label, and read boolean masks. It covers how duplicated() flags repeated rows. Removing them comes in the next chapter.
What duplicated() returns
DataFrame.duplicated() returns a boolean Series with one value per row. A row is True when an earlier row has exactly the same values in every column. The first occurrence is False, and each repeat after it is True.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2, 3],
"customer": ["Ann", "Bob", "Bob", "Cy"],
"total": [10.0, 20.0, 20.0, 5.0],
})
print(df.duplicated().tolist()) # [False, False, True, False]
print(df.duplicated().sum()) # 1The Series shares the index of the DataFrame, so you can use it as a mask. Because True counts as 1, sum() gives the number of repeated rows.
print(df[df.duplicated()])This prints only row 2, the second copy of Bob's order.
How the flags are decided
Three details matter in practice:
- Order matters. By default the first copy is kept as
False, so the result depends on the row order. - Matching is exact.
"Bob"and"bob "are different values, so those rows are not flagged. - Missing values compare as equal. Two rows with
NaNin the same column count as matching in that column.
Choosing the columns with subset
By default every column must match. Use subset to compare only the columns that define identity for your data, such as an ID.
orders = pd.DataFrame({
"order_id": [1, 2, 2],
"total": [10.0, 20.0, 25.0],
})
print(orders.duplicated().tolist()) # [False, False, False]
print(orders.duplicated(subset="order_id").tolist()) # [False, False, True]Order 2 appears twice with different totals. A full-row check misses it, while subset="order_id" catches it. That difference is often a data quality problem worth investigating before you delete anything.
Choosing which copy is flagged with keep
The keep parameter controls which rows are marked True.
| `keep` value | Effect |
|---|---|
| `"first"` (default) | Flags every repeat after the first occurrence. |
| `"last"` | Flags every earlier occurrence and leaves the last one `False`. |
| `False` | Flags every row that belongs to a duplicate group, including the first. |
print(df.duplicated(keep="last").tolist()) # [False, True, False, False]
print(df.duplicated(keep=False).tolist()) # [False, True, True, False]Use keep=False when you want to look at all the copies side by side:
print(df[df.duplicated(keep=False)])Common errors
- Forgetting
subsetwhen only an ID defines a duplicate, which hides rows that share a key but differ elsewhere. - Expecting
duplicated()to change the DataFrame. It only reports. Nothing is removed. - Passing a list-like of column names as a single string with commas. Use
subset=["a", "b"]for several columns. - Trusting the count before cleaning values. Stray spaces or mixed case make equal-looking rows count as different.
Exercise
A DataFrame has columns "user" and "plan", with rows ("a", "free"), ("a", "pro"), ("b", "free"). What does df.duplicated(subset="user", keep=False).tolist() return, and why?
Show answer
[True, True, False]. Rows 0 and 1 share the user "a", and keep=False flags every row in a duplicate group, including the first. User "b" appears once, so it is False. With the default keep="first", the result would be [False, True, False].