Sub topic 7
What counts as a duplicate row
This chapter assumes you can build a DataFrame and select columns by label, and that you know basic Python dictionaries and string methods such as strip and lower. It defines "duplicate" precisely, because every later step (flagging, dropping, keeping the latest record) depends on that definition.
The working definition
pandas has no notion of a "logical" duplicate. It treats two rows as duplicates when the values in the compared columns are equal, one column at a time. By default the compared columns are all of them.
Three rules follow from this:
- Rows are compared by value, not by position or label. The index is ignored.
- The first row in a group of equal rows is never flagged. Only later repeats are flagged.
- "Equal" means Python-level equality of the stored values, with one exception for missing values (covered below).
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]Rows 1 and 2 match in all three columns. Row 1 is the original, so it is False. Row 2 is the repeat, so it is True. The duplicated() method itself is covered in the next chapter. Here it only serves as a probe for the definition.
The index does not count
Two rows with different index labels can still be duplicates. The labels are not part of the row's data.
import pandas as pd
df = pd.DataFrame(
{"a": [1, 1], "b": ["x", "x"]},
index=["r1", "r2"],
)
print(df.duplicated().tolist()) # [False, True]If the label carries information, such as an ID stored as the index, move it into a column first with reset_index(). Otherwise it will be ignored.
Missing values match each other
Normally NaN == NaN is False in Python and NumPy. duplicated() deliberately departs from that rule. Two missing values in the same column count as equal.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"a": [1, 1],
"b": [np.nan, np.nan],
})
print(df.duplicated().tolist()) # [False, True]This is usually what you want, since two rows that are both "unknown" in the same place are the same record. It can also hide differences you care about. A row with a missing phone number is a duplicate of another row with a missing phone number, even if the real phone numbers would have differed. Decide whether that is acceptable before you drop anything.
Near-duplicates are not duplicates
Because comparison is exact, small differences make rows distinct. The most common causes are:
- Case:
"Bob"and"bob". - Whitespace:
"Bob"and"Bob ". - Types: the integer
1and the string"1". - Floating-point noise:
0.3and0.1 + 0.2.
import pandas as pd
names = pd.DataFrame({"customer": ["Bob", "bob", "Bob "]})
print(names.duplicated().tolist()) # [False, False, False]
ids = pd.DataFrame({"id": [1, "1"]})
print(ids.duplicated().tolist()) # [False, False]
floats = pd.DataFrame({"x": [0.3, 0.1 + 0.2]})
print(floats.duplicated().tolist()) # [False, False]The float case is a real gotcha. 0.1 + 0.2 evaluates to 0.30000000000000004, which is not the same number as 0.3. If your values come from calculations, round them first, for example with df["x"].round(2), and compare the rounded values.
For text, the fix is to normalize before comparing: strip whitespace and lowercase. The .str methods used for this are the same ones you use to clean column labels. A later chapter returns to normalizing before deduplicating, so for now the point is only to recognize that exact comparison is the reason such rows slip through.
Whole-row versus key-based duplicates
The default compares every column. That is often too strict. Suppose each order should appear once, but two rows share an order_id with different totals because one was a data-entry correction.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2, 3],
"total": [10.0, 20.0, 25.0, 5.0],
})
print(df.duplicated().tolist()) # [False, False, False, False]
print(df.duplicated(subset="order_id").tolist()) # [False, False, True, False]With all columns compared, no row repeats, because the totals differ. With subset="order_id", only order_id is compared, so row 2 is a repeat of row 1.
The subset argument changes the definition of "duplicate" itself. The same data can contain zero duplicates under one definition and one under another. Before cleaning, write down in plain words what identifies a record in your data. Common answers are:
| Data | What identifies one record | Compared columns |
|---|---|---|
| Order lines exported twice | Everything in the row | All columns (default) |
| One row per order | The order number | `order_id` |
| One row per user per day | User and date together | `["user", "date"]` |
| Latest status per user | The user | `user` |
If you pick the wrong key, you either keep rows you meant to remove or delete rows that were legitimately different. Both mistakes are silent: pandas gives no warning.
Rows with unhashable values
duplicated() hashes cell values to compare them. Cells that hold lists, dicts, or other unhashable objects cannot be hashed, so the call fails instead of returning a wrong answer.
import pandas as pd
df = pd.DataFrame({"tags": [["a"], ["a"]]})
try:
df.duplicated()
except TypeError:
print("TypeError: list cells are unhashable")
# Convert lists to tuples, which are hashable, then compare.
fixed = df.assign(tags=df["tags"].map(tuple))
print(fixed.duplicated().tolist()) # [False, True]Converting to tuples preserves order, so ["a", "b"] and ["b", "a"] stay distinct. If order should not matter, sort each list before converting.
Column order and column labels
Row comparison goes across the columns that are selected. Which columns are compared is decided by label when you use subset, so the order you list them in does not change the result. With the default, all columns are compared, and the result is the same however the columns are arranged.
Duplicate column labels are a separate problem. If two columns share a name, subset by that name becomes ambiguous. That case, and how to remove such columns, has its own chapter later in this tutorial.
A checklist for defining duplicates
Before you remove anything, answer these questions in order:
- What columns identify one record? Use all columns only if every field must match.
- Are text values in a consistent form (case, whitespace, spelling)?
- Are numbers stored with a consistent type, and are floats rounded where needed?
- Does a missing value in a compared column mean "same unknown" for your purposes?
- Do any cells hold lists or dicts that need converting first?
If every answer is satisfactory, the pandas definition of a duplicate matches yours, and the later steps of flagging, dropping and verifying will behave as you expect.
Exercise
A DataFrame has columns user and city, with rows ("Ann", "Oslo"), ("Ann", "Oslo "), ("ann", "Oslo"). The second row has a trailing space in the city, and the third has a lowercase user. How many rows does df.duplicated() flag, and why?
Show answer
None. Comparison is exact, so "Oslo" and "Oslo " are different strings, and "Ann" and "ann" are different strings. All three rows are distinct until you normalize the values with .str.strip() and .str.lower(). After normalizing both columns, rows 2 and 3 would be flagged as repeats of row 1.
Exercise
Two rows have identical values everywhere except the index labels "a" and "b", and both have NaN in the score column. Does df.duplicated() flag the second row? Name the two rules that decide this.
Show answer
Yes. The index is ignored, so the labels do not make the rows different, and missing values in the same column are treated as equal. The second row is therefore flagged as a duplicate of the first.
Exercise
A table holds one row per customer, but the same customer_id appears twice with different email values. df.duplicated() returns all False. Which change to the call would flag the repeat, and what does that change mean for your definition of a duplicate?
Show answer
Pass subset="customer_id". Under the default, rows are compared on every column, and the differing emails make them distinct. With subset="customer_id", the definition becomes "same customer", so the second row is flagged even though its email differs.