Sub topic 10
Controlling matches with subset and keep
This chapter assumes you can build a DataFrame, select columns by label, and read a boolean mask. You should also know that duplicated() flags repeated rows and drop_duplicates() removes them.
Why the defaults are not enough
By default, two rows count as duplicates only if every column matches. Real data often repeats a key, such as an order ID, while another column differs. In the example below, order 2 appears twice with different totals.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2, 3],
"customer": ["Ann", "Bob", "Bob", "Cy"],
"total": [10.0, 20.0, 25.0, 5.0],
})
print(len(df.drop_duplicates())) # 4No rows are removed, because the two order 2 rows differ in total. Two options change how matches are decided: subset and keep.
Choosing the columns with subset
subset names the columns that are compared. Other columns are ignored when deciding whether rows match. Pass one label or a list of labels.
by_order = df.drop_duplicates(subset="order_id")
print(by_order.index.tolist()) # [0, 1, 3]
by_pair = df.drop_duplicates(subset=["order_id", "customer"])
print(by_pair.index.tolist()) # [0, 1, 3]With a list, rows match only when all listed columns match. A wider subset finds fewer duplicates, and a narrower one finds more. Choose the columns that define identity in your data, which is usually a key.
Choosing which row survives with keep
Among a group of matching rows, keep decides what happens to each one.
| Value | Behavior |
|---|---|
| `"first"` (default) | Keeps the first row in each group and drops the later ones. |
| `"last"` | Keeps the last row in each group and drops the earlier ones. |
| `False` | Keeps none of the rows in any group that has a repeat. |
keep works the same way in duplicated(), where it decides which rows get True.
print(df.duplicated(subset="order_id").tolist())
# [False, False, True, False]
print(df.duplicated(subset="order_id", keep="last").tolist())
# [False, True, False, False]
print(df.duplicated(subset="order_id", keep=False).tolist())
# [False, True, True, False]With keep=False, every member of a repeated group is flagged. That is useful for inspecting all the conflicting rows together, as in the next example.
conflicts = df[df.duplicated(subset="order_id", keep=False)]
print(conflicts["total"].tolist()) # [20.0, 25.0]
kept_last = df.drop_duplicates(subset="order_id", keep="last")
print(kept_last.index.tolist()) # [0, 2, 3]
only_unique = df.drop_duplicates(subset="order_id", keep=False)
print(only_unique.index.tolist()) # [0, 3]Checking the choice before you drop
A narrow subset can silently discard data that differs. Before dropping rows, flag them with keep=False and look at what would be lost. Count the duplicates, then compare the shapes before and after.
n_flagged = df.duplicated(subset="order_id").sum()
cleaned = df.drop_duplicates(subset="order_id")
print(n_flagged, len(df) - len(cleaned)) # 1 1The two numbers agree, as they should. If they differ, the subset or the keep value is not what you think it is.
Common errors
- Passing a column label that does not exist raises a
KeyError. Checkdf.columnsfirst. - Writing
df.drop_duplicates(subset="order_id")without assigning the result leavesdfunchanged, because the method returns a new DataFrame. - Using
keep=Falseand expecting one survivor. It removes every row in a repeated group, so those keys disappear entirely.
Exercise
A DataFrame has columns "user", "day", and "score", and some users have several rows on the same day. Which call keeps exactly one row per user and day, using the row that appears last? Which call returns only the rows whose user and day combination appears once?
Show answer
Use df.dropduplicates(subset=["user", "day"], keep="last") for one row per user and day. Use df.dropduplicates(subset=["user", "day"], keep=False) for the combinations that appear exactly once.