Sub topic 10
Controlling matches with subset and keep
This chapter covers the two options that decide what duplicated() and drop_duplicates() treat as a duplicate and which row survives. It assumes you can build a DataFrame, select columns by label, and read a boolean mask. It also assumes you have seen drop_duplicates() called with no arguments.
The two questions every call answers
Every deduplication call answers two questions:
- Which columns must match for two rows to count as the same record?
subsetanswers this. - When several rows match, which one is kept?
keepanswers this.
The defaults are subset=None, which compares every column, and keep="first". Defaults are safe but often wrong for real data. An order table may repeat an order_id with a corrected total. Comparing all columns treats those rows as different, so nothing is removed.
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().tolist())
# [False, False, True, False, False]
print(df.duplicated(subset="order_id").tolist())
# [False, False, True, False, True]Row 4 repeats order_id 3 but has a different total. It is a duplicate by key, but not a full-row duplicate.
Choosing columns with subset
subset takes one column label or a list of labels. Only those columns are compared. Every other column is ignored for matching, but it still travels with the rows.
print(df.duplicated(subset=["order_id", "customer"]).tolist())
# [False, False, True, False, True]With a list, all listed columns must match at once. This is a composite key. Passing ["order_id", "customer"] means "same order and same customer". The order of labels in the list does not matter.
Some details to remember:
- A single string is accepted, so
subset="order_id"andsubset=["order_id"]behave the same. - Labels must exist. A typo raises
KeyError, unlikerename(), which silently ignores unmatched keys by default. subset=[]is not a way to say "no columns". Leave the argument out to compare all columns.- Columns outside
subsetare never compared, so differing values in them are lost for the rows you drop.
try:
df.drop_duplicates(subset="orderid")
except KeyError:
print("KeyError: no column named 'orderid'")Choosing survivors with keep
keep has three values.
| Value | Rows flagged by `duplicated()` | Rows kept by `drop_duplicates()` |
|---|---|---|
| `"first"` (default) | Every repeat after the first | The first row of each group |
| `"last"` | Every row before the last | The last row of each group |
| `False` | Every row in a group of two or more | Only rows that are unique |
The wording "first" and "last" refers to row position in the DataFrame as it stands when you call the method. It does not mean earliest or latest by time. If your data is not sorted by time, keep="last" does not give you the most recent record. The chapter on keeping the latest record covers the sorting step.
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]Here is how the three settings differ for the order_id 3 group, which has totals 5.0 and 7.5:
first = df.drop_duplicates(subset="order_id")
last = df.drop_duplicates(subset="order_id", keep="last")
none_left = df.drop_duplicates(subset="order_id", keep=False)
print(first.loc[first["order_id"] == 3, "total"].tolist()) # [5.0]
print(last.loc[last["order_id"] == 3, "total"].tolist()) # [7.5]
print(none_left["order_id"].tolist()) # [1]keep=False is useful for isolating records that have no repeat, or for removing every row involved in a conflict so you can review the group by hand. For review, it is often better to keep the rows and look at them:
conflicts = df[df.duplicated(subset="order_id", keep=False)]
print(conflicts["order_id"].tolist()) # [2, 2, 3, 3]How the decision flows
The diagram shows what happens inside one call when subset and keep are set.
Missing values count as equal
pandas treats two missing values as equal when matching rows. If your subset column has several NaN or None entries, they are all considered duplicates of each other.
people = pd.DataFrame({
"email": ["[email protected]", None, None, "[email protected]"],
"name": ["A", "B", "C", "D"],
})
print(people.duplicated(subset="email").tolist())
# [False, False, True, False]Person C is flagged only because B also has no email. That is rarely what you want. To protect rows with missing keys, combine the flag with a mask for non-missing values:
is_repeat = people.duplicated(subset="email") & people["email"].notna()
cleaned = people[~is_repeat]
print(cleaned["name"].tolist()) # ['A', 'B', 'C', 'D']Matching is exact
Matching compares values exactly. "Ann" and "ann" differ, and so do "Ann" and "Ann " with a trailing space. Floats are compared by exact equality, so 0.1 + 0.2 and 0.3 do not match. The integer 1 and the float 1.0 do match, because they compare equal. The normalization chapter covers cleaning text before deduplicating. For now, treat an unexpectedly low duplicate count as a sign of near-duplicates, not as proof the data is clean.
Keeping the same options in both methods
duplicated() and drop_duplicates() accept the same subset and keep arguments and apply the same rules. This gives you a reliable workflow: flag first, inspect, then drop with identical arguments.
key = ["order_id", "customer"]
flags = df.duplicated(subset=key, keep="last")
print(flags.sum()) # 2
result = df.drop_duplicates(subset=key, keep="last")
print(len(df) - len(result)) # 2
print(result.index.tolist()) # [0, 2, 4]The count of True flags equals the number of rows removed, as long as keep is "first" or "last". With keep=False the numbers differ. Every row in a repeated group is flagged and dropped, including the first one.
Notice that result.index is [0, 2, 4]. The surviving rows keep their original labels, so the index has gaps. Resetting it is the topic of the next chapter, using ignore_index=True.
Common mistakes
- Dropping on the wrong key. Deduplicating on
customeralone removes every repeat order from that customer. The key should identify one record, not one entity. - Assuming
keep="last"means newest. It means last by position. Sort first when time matters. - Forgetting to assign.
drop_duplicates()returns a new DataFrame. Callingdf.drop_duplicates(subset="order_id")on its own line changes nothing. Assign the result, or passinplace=True, though assignment is the clearer habit. - Using
keep=Falseand expecting one row per group. It removes the whole group. - Ignoring the data you discard. Columns outside
subsetcan hold conflicting values, such as the two totals above. Check the conflicts withkeep=Falsebefore choosing a survivor.
Exercise
A DataFrame has columns sku, warehouse, and count, with rows (A, N, 5), (A, N, 7), (A, S, 7), (B, N, 2). You call df.drop_duplicates(subset=["sku", "warehouse"], keep=False). Which rows remain, and what would change if you used keep="last" instead?
Show answer
With keep=False, only (A, S, 7) and (B, N, 2) remain, because the two (A, N) rows form a repeated group and both are dropped. With keep="last", the rows (A, N, 7), (A, S, 7), and (B, N, 2) remain. The (A, N, 5) row is dropped and the other (A, N) row survives.
Exercise
A column email contains None in three rows. You run df.drop_duplicates(subset="email"). How many of those three rows survive, and how can you keep all of them?
Show answer
Only one survives, because missing values match each other. To keep all of them, build a mask such as df.duplicated(subset="email") & df["email"].notna() and keep the rows where that mask is False, using df[~mask].