Sub topic 9
Finding Duplicate Rows with duplicated
This chapter assumes you can build a pandas DataFrame and select columns from it. You should also know that a boolean Series can filter rows. By the end you will be able to flag repeated rows, choose which copy counts as the "original", and inspect duplicates before you delete anything.
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. Two rows count as repeats when every compared column holds an equal value. The returned Series uses the same index as the DataFrame, so you can use it directly as a filter.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
flags = df.duplicated()
print(flags.tolist()) # [False, False, True, False, True, False, False]
print(flags.sum()) # 2 rows repeat an earlier row
print(df[flags]) # rows 2 and 4Row 2 (Oslo, free) repeats row 0. Row 4 (Rome, pro) repeats row 1. Rows 0 and 1 are not flagged, because nothing before them matches. The method flags only the repeats, not the first occurrence.
Choosing which columns to compare
By default, duplicated compares all columns. That is rarely what you want when the table has an identifier column, because a unique ID makes every row distinct. The subset argument limits the comparison to the columns that define a duplicate in your data.
df2 = df.assign(user_id=[1, 2, 3, 4, 5, 6, 7])
print(df2.duplicated().sum()) # 0, user_id differs in every row
print(df2.duplicated(subset=["city", "plan"]).sum()) # 2
print(df2.duplicated(subset="city").sum()) # 3, a single column name also worksBefore you call duplicated, decide what "the same record" means. The answer depends on the data, not on pandas. Two orders with the same customer and product might be a data-entry error, or they might be two real purchases.
Choosing which copy is kept
The keep argument controls which rows in a group of identical rows are treated as the original.
| `keep` value | Rows flagged `True` | Typical use |
|---|---|---|
| `"first"` (default) | Every repeat after the first occurrence | Keep the earliest record |
| `"last"` | Every occurrence before the last one | Keep the most recent record |
| `False` | Every row that belongs to a repeated group | Inspect or remove all copies |
print(df.duplicated(keep="first").tolist()) # [False, False, True, False, True, False, False]
print(df.duplicated(keep="last").tolist()) # [True, True, False, False, False, False, False]
print(df.duplicated(keep=False).tolist()) # [True, True, True, False, True, False, False]With keep="last", rows 0 and 1 are flagged because identical rows (2 and 4) come later. With keep=False, all four rows in the two repeated groups are flagged, including the first occurrences.
The default "first" depends on row order. If your data is not sorted the way you expect, "first" may not be the record you want to keep. Sort first, for example by a timestamp, and then call duplicated.
Missing values count as equal
Most pandas comparisons treat a missing value as unequal to everything, including another missing value. duplicated is different: it treats two missing values in the same column as the same value.
dup_missing = pd.DataFrame({
"city": ["Oslo", None, None],
"plan": ["free", "free", "free"],
})
print(dup_missing.duplicated().tolist()) # [False, False, True]Row 2 is flagged because its city is missing and its plan matches row 1. This is usually what you want when you are looking for repeated records. It can surprise you when the missing value means "unknown", because two unknown cities may be different places. If that matters, fill the missing values with distinct placeholders, or exclude those rows from the check.
Inspecting duplicates before acting
Looking at the repeated groups before you remove anything is safer than deleting straight away. Use keep=False so that every member of a group appears, then sort so the groups sit together.
repeated = df[df.duplicated(keep=False)].sort_values(["city", "plan"])
print(repeated)
# city plan
# 0 Oslo free
# 2 Oslo free
# 1 Rome pro
# 4 Rome proThe original row labels stay on the filtered result, so you can trace each row back to the source data. To see how large each group is, count the combinations and keep those that occur more than once.
combo_counts = df.value_counts(["city", "plan"])
print(combo_counts[combo_counts > 1]) # Oslo/free: 2 and Rome/pro: 2value_counts drops rows that contain missing values by default, so the row with a missing city does not appear in this count. duplicated does include it. If you compare the two results, pass dropna=False to value_counts to make them agree.
Measuring how much duplication you have
Because the result is boolean, summing it gives the number of flagged rows. Taking its mean gives the share of flagged rows.
n_repeats = df.duplicated().sum() # 2
share = df.duplicated().mean() # 2 / 7, about 0.286
print(n_repeats, round(share, 3))The count depends on keep. With keep=False you get 4, the number of rows involved in duplication. With keep="first" you get 2, the number of rows a deduplication would remove. Choose the one that answers your question and say which one you reported.
Series and index variants
A Series has its own duplicated. It flags repeated values in one column and accepts the same keep argument.
print(df["city"].duplicated().tolist())
# [False, False, True, False, True, True, False]Note that three repeats here is more than the two repeated rows above. Row 5 (Oslo, pro) repeats an earlier city but not an earlier row. Flagging repeated values in one column and flagging repeated rows are different questions.
An Index also has duplicated, used as df.index.duplicated(). This is the quick check for repeated row labels, which can cause confusing results when you select with .loc.
Common mistakes
- Expecting the first occurrence to be flagged. With the default
keep="first", it is not. Usekeep=Falseto see whole groups. - Comparing too many columns. An ID, timestamp, or other always-unique column hides real duplicates. Pass
subset. - Near-duplicates are not duplicates.
"Oslo","oslo"and"Oslo "are three different values. Normalize case and whitespace first, for example withdf["city"].str.strip().str.lower(), then compare. - Passing the wrong type to
subset. Use a column name or a list of names. A name that does not exist raises aKeyError. - Assuming the index matters.
duplicatedignores the index labels. Two rows with different labels but the same values are duplicates. - Assuming floats are exact. Values such as
0.1 + 0.2and0.3differ in the last bits, soduplicatedtreats them as different. Round first if you need approximate matching.
Exercise
A DataFrame has columns orderid, customer and product, and orderid is unique per row. You want to find customers who bought the same product more than once, and you want to see every matching row, including the first purchase. Write the expression that returns those rows.
Show answer
df[df.duplicated(subset=["customer", "product"], keep=False)]. The subset leaves out order_id, which would make every row distinct. keep=False flags the first occurrence as well as the repeats, so every purchase in a repeated group appears.
Exercise
For the DataFrame in this chapter, df.duplicated(keep="first").sum() returns 2 and df.duplicated(keep=False).sum() returns 4. Explain why the numbers differ, and say which one tells you how many rows a deduplication would remove.
Show answer
With keep="first" only the repeats after the first occurrence are flagged: rows 2 and 4. With keep=False, both rows of each repeated group are flagged: rows 0, 1, 2 and 4. Deduplication keeps one row per group, so the keep="first" count of 2 is the number of rows it would remove.