Sub topic 12
Keeping the latest record per key
This chapter assumes you know how to create a DataFrame, select columns by label, and call drop_duplicates() with subset and keep. Here you combine sorting with deduplication to keep the most recent row for each key.
The problem
Data often holds several versions of the same entity. A table of user events might have one row per update, and you want only the current state of each user. drop_duplicates() does not know which row is newest. It only knows row order, and keep="first" or keep="last" refers to that order.
So the recipe has two steps:
- Sort so the row you want to keep sits in the position that
keepselects. - Call
drop_duplicates()withsubsetset to the key column and the matchingkeepvalue.
Worked example
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']]sort_values("updated") orders rows from oldest to newest. Within user a, the January row comes before the February row. keep="last" then retains the final row of each group, which is the newest. The subset="user" argument makes two rows count as duplicates when only their user values match, even though updated and plan differ.
Equivalent form with keep="first"
You can sort in descending order and keep the first row instead. Both give the same result.
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", ascending=False)
.drop_duplicates(subset="user", keep="first")
)
print(latest["user"].tolist()) # ['a', 'b'] or ['b', 'a'] depending on the sortThe row order of the result follows the sorted order, not the original order. If you need a stable presentation, sort the result again or pass ignore_index=True to renumber the rows.
Common errors
- Forgetting to sort. Without
sort_values,keep="last"keeps whichever row happens to be last in the file. That may be the newest, or it may not. - Sorting text dates. Strings like
"2026-02-01"sort correctly only in ISO format (year, month, day). A format such as"01/02/2026"sorts alphabetically and gives wrong results. Convert withpd.to_datetimefirst. - Dropping the sort column by accident.
subsetlists only the columns that define a match. If you includeupdatedinsubset, rows with different dates are no longer duplicates, and nothing is removed. - Ties. If two rows for the same key share the same timestamp, the one kept depends on their prior order. Add a second sort column, such as an ID, to make the choice deterministic.
Checking the result
After deduplication, confirm that each key appears once and that you kept the rows you meant to keep.
print(latest["user"].is_unique) # True
print(len(latest)) # 2Exercise
A DataFrame df has columns sku, price, and checked_at (datetime values). Write the expression that keeps the cheapest-to-newest record rule "the most recently checked row for each sku". Which sort column and which keep value do you use?
Show answer
Sort by checked_at ascending and keep the last row per sku: df.sort_values("checked_at").drop_duplicates(subset="sku", keep="last"). Equivalently, sort descending and use keep="first".