Sub topic 3
Controlling Matches with `subset` and `keep` in pandas
Assume you can create a pandas DataFrame, select columns by label, and use basic Python dictionaries and string methods. This chapter focuses on controlling which duplicate rows pandas matches and retains.
Choosing rows with `subset` and `keep`
drop_duplicates() compares complete rows by default. Use subset to compare only selected columns. The keep argument chooses which matching row remains:
keep="first"keeps the first matching row.keep="last"keeps the last matching row.keep=Falseremoves every row in a matching group.
import pandas as pd
events = pd.DataFrame({
"user": ["a", "a", "b"],
"updated": ["2026-01-01", "2026-02-01", "2026-01-15"],
"plan": ["free", "pro", "free"],
})
latest = (
events.sort_values("updated")
.drop_duplicates(subset="user", keep="last")
)
print(latest[["user", "plan"]].sort_values("user").values.tolist())
# [['a', 'pro'], ['b', 'free']]The two rows for user a differ in updated and plan, so they are not complete-row duplicates. With subset="user", pandas treats them as duplicates for this operation.
What happens to the index
Removing rows does not automatically renumber the index. Use ignore_index=True when the result should have a fresh consecutive index.
clean = events.drop_duplicates(subset="user", keep="last", ignore_index=True)
print(clean.index.tolist()) # [0, 1]Keeping the latest record per key
Sort by the time column first. Then keep="last" retains the latest row in each key group. If the date is stored as text in a non-sortable format, convert it with pd.to_datetime() before sorting.
Normalizing values before deduplicating
Values that differ only in formatting are different to pandas. Trim whitespace and standardize case before deduplication.
df["email"] = df["email"].str.strip().str.lower()
df = df.drop_duplicates(subset="email", ignore_index=True)Handling duplicate column labels
Column labels can also repeat. Keep the first occurrence with a boolean column mask:
df = df.loc[:, ~df.columns.duplicated()]Verifying the result
Check the row count, index, and remaining duplicate keys after cleanup.
Exercise
Which option keeps the latest row for each customer after sorting by date?
Show answer
Use drop_duplicates(subset="customer", keep="last") after sorting the date column in ascending order.