Sub topic 8
Finding duplicates with duplicated()
This chapter assumes you can build a DataFrame, select columns by label, and use Boolean masks to filter rows. You should also know that a pandas Series of True and False values can select rows. The previous chapter defined a duplicate row as one whose values match an earlier row across the columns you compare. Here you will measure 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 a row seen earlier. It does not change the DataFrame.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2, 3, 3],
"customer": ["Ann", "Bob", "Bob", "Cy", "Cy"],
"total": [10.0, 20.0, 20.0, 5.0, 7.5],
})
flags = df.duplicated()
print(flags.tolist()) # [False, False, True, False, False]
print(flags.sum()) # 1
print(flags.mean()) # 0.2
print(df[flags])
# order_id customer total
# 2 2 Bob 20.0Row 2 repeats row 1 in all three columns, so it is flagged. Row 4 shares order_id and customer with row 3 but has a different total. By default every column is compared, so row 4 is not a duplicate.
Because the result is a Boolean Series, three operations come for free:
.sum()counts the flagged rows, becauseTruecounts as 1..mean()gives the fraction of rows that are flagged.- Passing the Series to
df[...]selects the flagged rows.
The returned Series uses the same index as the DataFrame. Selecting with it works even when the index is not the default 0, 1, 2, ....
The first occurrence is not flagged
By default, duplicated() flags every repeat after the first occurrence. The first row of each group is False. This is why the count above is 1 and not 2. The number you get is the number of rows that drop_duplicates() would remove, not the number of rows involved in duplication.
Choosing which rows to compare with subset
The subset parameter limits the comparison to some columns. It accepts a single label or a list of labels. Other columns are ignored when deciding whether two rows match.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2, 3, 3],
"customer": ["Ann", "Bob", "Bob", "Cy", "Cy"],
"total": [10.0, 20.0, 20.0, 5.0, 7.5],
})
print(df.duplicated(subset="order_id").tolist())
# [False, False, True, False, True]
print(df.duplicated(subset=["order_id", "customer"]).sum()) # 2With subset="order_id", row 4 is now flagged, because its order_id of 3 appeared in row 3. Whether that is correct depends on your data. If order_id should be unique, rows 3 and 4 are a conflict worth investigating, not a harmless copy.
A label in subset that does not exist raises a KeyError. This is a useful safeguard against typos.
Choosing which occurrence counts with keep
The keep parameter controls which rows in a group of matches are left unflagged.
| `keep` value | Unflagged row in each group | Flagged rows |
|---|---|---|
| `"first"` (default) | The first occurrence | All later occurrences |
| `"last"` | The last occurrence | All earlier occurrences |
| `False` | None | Every row in the group |
Here is the difference on the same data:
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2, 3, 3],
"customer": ["Ann", "Bob", "Bob", "Cy", "Cy"],
"total": [10.0, 20.0, 20.0, 5.0, 7.5],
})
print(df.duplicated(subset="order_id", keep="first").tolist())
# [False, False, True, False, True]
print(df.duplicated(subset="order_id", keep="last").tolist())
# [False, True, False, True, False]
print(df.duplicated(subset="order_id", keep=False).tolist())
# [False, True, True, True, True]Use keep=False when you want to inspect the whole group, not just the extra rows. Row 0 has a unique order_id, so it is False under every setting. The other four rows belong to groups with more than one member.
The next chapter shows how the same subset and keep options work in drop_duplicates(). The meaning is identical, so what you learn here carries over.
Looking at duplicate groups before removing them
Flagged rows alone can be hard to judge, because the original row they repeat is not flagged. To see each group together, use keep=False and sort by the key.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2, 3, 3],
"customer": ["Ann", "Bob", "Bob", "Cy", "Cy"],
"total": [10.0, 20.0, 20.0, 5.0, 7.5],
})
group_mask = df.duplicated(subset="order_id", keep=False)
conflicts = df[group_mask].sort_values("order_id")
print(conflicts)
# order_id customer total
# 1 2 Bob 20.0
# 2 2 Bob 20.0
# 3 3 Cy 5.0
# 4 3 Cy 7.5Now you can see two different situations. The two rows for order 2 are identical, so either can be dropped. The two rows for order 3 disagree on total, so dropping one loses information. duplicated() with default settings would hide this difference, since it only reports that a repeat exists.
Edge cases in how values are compared
Several details change which rows count as equal.
- Missing values match each other. Unlike ordinary comparison, where
NaN == NaNisFalse,duplicated()treats two missing values in the same column as equal. - Float comparison is exact. Values that differ by rounding error are not duplicates.
- Text must match exactly.
"Bob"and"bob "are different values. - The index is ignored. Only column values are compared, so identical rows with different index labels are still duplicates.
import numpy as np
import pandas as pd
missing = pd.DataFrame({"a": [np.nan, np.nan], "b": [1, 1]})
print(missing.duplicated().tolist()) # [False, True]
floats = pd.Series([0.1 + 0.2, 0.3])
print(floats.duplicated().tolist()) # [False, False]
text = pd.Series(["Bob", "bob ", "Bob"])
print(text.duplicated().tolist()) # [False, False, True]The float case is a common source of surprise. 0.1 + 0.2 evaluates to 0.30000000000000004, which is not equal to 0.3. If your numbers come from calculations, round them before comparing, for example with df["total"].round(2). The text case is why cleaning values comes before deduplicating. A later chapter covers normalizing strings.
Cells that hold unhashable objects, such as lists or dictionaries, cannot be compared this way. duplicated() raises a TypeError for them. Convert such cells to tuples or strings first.
Using duplicated() on a Series or an Index
Series.duplicated() and Index.duplicated() work the same way on one-dimensional data, and they accept keep. df.columns.duplicated() is the tool for repeated column labels, which a later chapter covers. For a single column, a quick check looks like this:
import pandas as pd
customers = pd.Series(["Ann", "Bob", "Bob", "Cy"])
print(customers.duplicated().tolist()) # [False, False, True, False]
print(customers[customers.duplicated()].tolist()) # ['Bob']Making duplicate counts a habit
A short report makes cleanup easy to verify later. Record the numbers before you change anything:
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2, 3, 3],
"customer": ["Ann", "Bob", "Bob", "Cy", "Cy"],
"total": [10.0, 20.0, 20.0, 5.0, 7.5],
})
full_repeats = df.duplicated().sum()
key_repeats = df.duplicated(subset="order_id").sum()
rows_in_groups = df.duplicated(subset="order_id", keep=False).sum()
print("rows:", len(df)) # rows: 5
print("exact repeats:", full_repeats) # exact repeats: 1
print("repeated keys:", key_repeats) # repeated keys: 2
print("rows in groups:", rows_in_groups) # rows in groups: 4The difference between exact repeats (1) and repeated keys (2) tells you that one key has conflicting values. That is the kind of finding to resolve before dropping anything.
Common errors
- Using the result as a filter when you meant the opposite.
df[df.duplicated()]selects the repeats.df[~df.duplicated()]selects the rows to keep. The~operator inverts a Boolean Series. - Expecting the first occurrence to be flagged. With the default
keep="first", it is not. Usekeep=Falseto include it. - Passing a list where a label is expected, or the reverse. Both forms of
subsetwork, but a misspelled name raisesKeyError. - Forgetting that
duplicated()does not modify the DataFrame. It only reports. The removal step isdrop_duplicates().
Exercise
A DataFrame has columns email and signup_date, and df.duplicated(subset="email").sum() returns 3. Write the expression that returns every row whose email appears more than once, including the first occurrence of each, sorted by email. Why can the number of rows returned be larger than 3?
Show answer
Use df[df.duplicated(subset="email", keep=False)].sort_values("email"). The sum of 3 counts only the repeats after each first occurrence. keep=False also includes the first row of every group, so the result has at least 4 rows, and exactly 3 plus the number of distinct repeated emails.
Exercise
Given s = pd.Series([1.0, float("nan"), float("nan"), 1.0]), what does s.duplicated(keep="last").tolist() return, and why?
Show answer
It returns [True, True, False, False]. With keep="last", the final occurrence in each group is unflagged. The two 1.0 values form one group, so the first is flagged. The two missing values also form one group, because duplicated() treats missing values as equal, so the first NaN is flagged.