Sub topic 12
Keeping the latest record per key
This chapter assumes you know drop_duplicates() with its subset and keep options, and basic sorting with sort_values(). It also assumes you can convert text to dates with pd.to_datetime().
The problem
Many tables hold several rows for the same entity. A user table logs every plan change. A sensor table logs every reading. A customer export contains one row per edit. Usually you want one row per entity, the most recent one.
The entity identifier is the key. Here the key is the user column. A key can also span several columns, such as ["user", "device"].
Calling drop_duplicates(subset="user") alone is not enough, because it decides by row position and ignores dates. The rest of this chapter shows how to make position match recency.
Sort first, then drop
drop_duplicates() with keep="last" retains the last row of each group of matches, in the DataFrame's current row order. So if you sort the rows from oldest to newest, "last" means "newest".
import pandas as pd
events = pd.DataFrame({
"user": ["a", "b", "a", "a", "b"],
"updated": ["2026-03-10", "2026-03-01", "2026-02-01",
"2026-01-01", "2026-01-15"],
"plan": ["enterprise", "pro", "pro", "free", "free"],
})
# Wrong: keeps whichever row happens to sit last in the file.
naive = events.drop_duplicates(subset="user", keep="last")
print(naive[["user", "plan"]].values.tolist())
# [['a', 'free'], ['b', 'free']]
# Right: order by date, then keep the last row per user.
latest = (
events.sort_values("updated")
.drop_duplicates(subset="user", keep="last")
)
print(latest.sort_values("user")[["user", "plan"]].values.tolist())
# [['a', 'enterprise'], ['b', 'pro']]The naive call returns the oldest rows because the file lists them last. The sorted version gives the right answer.
<br>
You can also sort in descending order and keep the first row. The two approaches are equivalent:
latest = (
events.sort_values("updated", ascending=False)
.drop_duplicates(subset="user", keep="first")
)Pick one style and use it consistently. Ascending with keep="last" is common because the sorted output reads chronologically.
Sort on a real date type
sort_values() sorts text alphabetically, character by character. ISO dates such as 2026-03-10 sort correctly as text because the year comes first and every field is zero-padded. Other formats break this.
import pandas as pd
raw = pd.DataFrame({
"user": ["a", "a"],
"updated": ["9 Jan 2026", "10 Jan 2026"],
"plan": ["old", "new"],
})
# As text, "10 Jan 2026" sorts before "9 Jan 2026" because "1" < "9".
wrong = raw.sort_values("updated").drop_duplicates(subset="user", keep="last")
print(wrong["plan"].tolist()) # ['old']
raw["updated"] = pd.to_datetime(raw["updated"], format="%d %b %Y")
right = raw.sort_values("updated").drop_duplicates(subset="user", keep="last")
print(right["plan"].tolist()) # ['new']Both versions run without errors, so nothing warns you about the wrong one. Convert the column with pd.to_datetime() before sorting, and pass an explicit format when you know it.
Missing dates and ties
Two situations make "latest" ambiguous. In both, decide the rule deliberately instead of accepting the default.
Missing timestamps
sort_values() places missing values (NaN or NaT) at the end by default. With keep="last", a row with no date would therefore win.
import pandas as pd
rows = pd.DataFrame({
"user": ["a", "a"],
"updated": pd.to_datetime(["2026-01-01", None]),
"plan": ["free", "unknown"],
})
default = rows.sort_values("updated").drop_duplicates("user", keep="last")
print(default["plan"].tolist()) # ['unknown']
safer = (
rows.sort_values("updated", na_position="first")
.drop_duplicates("user", keep="last")
)
print(safer["plan"].tolist()) # ['free']na_position="first" makes undated rows lose to any dated row. If undated rows are meaningless, remove them first with rows.dropna(subset=["updated"]).
Ties
Two rows for the same key can share the same timestamp. Then the sort alone does not say which is newer. Add a tiebreaker column, such as a version number or an auto-incrementing ID:
latest = (
events.sort_values(["updated", "version"])
.drop_duplicates(subset="user", keep="last")
)This assumes events has a version column. Sorting by several columns is stable, so rows that still tie keep their original relative order. A single-column sort_values() uses quicksort by default, which does not guarantee that. If file order is your tiebreaker, pass kind="stable" so the later row in the file wins.
<br>
What happens to the index
Sorting reorders the index along with the rows, and drop_duplicates() removes labels. The result has an index that is neither sorted nor contiguous.
import pandas as pd
events = pd.DataFrame({
"user": ["a", "b", "a", "a", "b"],
"updated": pd.to_datetime(["2026-03-10", "2026-03-01", "2026-02-01",
"2026-01-01", "2026-01-15"]),
"plan": ["enterprise", "pro", "pro", "free", "free"],
})
latest = (
events.sort_values("updated")
.drop_duplicates(subset="user", keep="last")
)
print(latest.index.tolist()) # [1, 0]
print(latest.sort_index().index.tolist()) # [0, 1]
fresh = (
events.sort_values("updated")
.drop_duplicates(subset="user", keep="last", ignore_index=True)
)
print(fresh.index.tolist()) # [0, 1]
print(fresh["user"].tolist()) # ['b', 'a']Use sort_index() to restore the original file order, which keeps the surviving rows' original labels. Use ignore_index=True when the old labels carry no meaning. It renumbers the rows 0 to n-1 in the current (date-sorted) order.
An alternative with groupby
You can select the newest row per key without sorting the whole table:
import pandas as pd
events = pd.DataFrame({
"user": ["a", "b", "a", "a", "b"],
"updated": pd.to_datetime(["2026-03-10", "2026-03-01", "2026-02-01",
"2026-01-01", "2026-01-15"]),
"plan": ["enterprise", "pro", "pro", "free", "free"],
})
via_idxmax = events.loc[events.groupby("user")["updated"].idxmax()]
print(via_idxmax[["user", "plan"]].values.tolist())
# [['a', 'enterprise'], ['b', 'pro']]idxmax() returns the index label of the largest date in each group, and loc fetches those rows.
| Approach | Strengths | Watch out for |
|---|---|---|
| `sort_values()` + `drop_duplicates(keep="last")` | Short, handles multi-column keys and tiebreakers | Sorts the whole table, and missing dates sort last |
| `groupby(key)[col].idxmax()` | Clear intent, no full sort | Needs a unique index, skips missing values, and picks the first of tied maxima |
| `sort_values()` + `groupby(key).tail(1)` | Easy to extend to the last N rows per key | Slower than `drop_duplicates()` on large tables |
For most cleanup jobs, sort plus drop_duplicates() is the simplest choice. Switch to idxmax() when the index is unique and you want the selection rule to be explicit.
Normalize the key first
subset="user" compares values exactly. "Ann", "ann" and "ann " count as three different users, so all three rows would survive. Clean the key before you deduplicate:
import pandas as pd
people = pd.DataFrame({
"user": ["Ann", "ann ", "Bob"],
"updated": pd.to_datetime(["2026-01-01", "2026-02-01", "2026-01-10"]),
"plan": ["free", "pro", "free"],
})
people["user"] = people["user"].str.strip().str.lower()
latest = (
people.sort_values("updated")
.drop_duplicates(subset="user", keep="last")
)
print(latest.sort_values("user")[["user", "plan"]].values.tolist())
# [['ann', 'pro'], ['bob', 'free']]Verify the result
A correct run satisfies two checks: each key appears once, and no key disappeared. Write them as assertions so a bad input fails loudly:
import pandas as pd
events = pd.DataFrame({
"user": ["a", "b", "a", "a", "b"],
"updated": pd.to_datetime(["2026-03-10", "2026-03-01", "2026-02-01",
"2026-01-01", "2026-01-15"]),
"plan": ["enterprise", "pro", "pro", "free", "free"],
})
latest = (
events.sort_values("updated", na_position="first")
.drop_duplicates(subset="user", keep="last")
.sort_index()
)
assert latest["user"].is_unique
assert len(latest) == events["user"].nunique()
assert latest["updated"].notna().all()
print(events.shape, "->", latest.shape) # (5, 3) -> (2, 3)nunique() skips missing keys by default, so this check assumes the key column has no missing values. Also compare the kept dates against the maximum per key, for example with events.groupby("user")["updated"].max().
Exercise
A DataFrame accounts has columns account (text with stray spaces and mixed case, such as " ACME "), ts (text like "5 Mar 2026" and "12 Mar 2026") and balance. Describe the steps and the key calls to keep the most recent row per account. Include how you would check the result.
Show answer
First normalize the key with accounts["account"] = accounts["account"].str.strip().str.lower(). Next convert the dates with accounts["ts"] = pd.to_datetime(accounts["ts"], format="%d %b %Y"). Without this, "12 Mar 2026" sorts before "5 Mar 2026" as text. Then call accounts.sort_values("ts", na_position="first").drop_duplicates(subset="account", keep="last"). Optionally add ignore_index=True or call .sort_index() to tidy the index. Verify with assert result["account"].is_unique and assert len(result) == accounts["account"].nunique().