skip to content

In pandas, how do you keep only each contact's most recent sign-up when a CRM export repeats contacts across sign-ups?

level: middleimportance: must knowfreq 66%

answer

  1. position decides, not dates
  2. sort first, then deduplicate
  3. subset is the contact key
  4. where missing dates sort
  5. relabel the survivors

basics

~10 s

drop_duplicates keeps a copy by row position, not by date, so sort first: crm.sort_values('signup', ascending=False).drop_duplicates('contact_id') keeps each contact's latest dated row; ignore_index=True renumbers the result.

solid answer

~40 s

`drop_duplicates` knows nothing about dates: `keep='first'` and `keep='last'` refer to row position in the frame as it stands. So the recipe is to sort, then deduplicate on the key: `crm.sort_values('signup').drop_duplicates('contact_id', keep='last')`, or sort descending and keep the default `'first'`. The two are not equal when `signup` has missing dates, because `sort_values` puts `NaT` last in both directions by default: the ascending version then keeps the undated row as the "latest", the descending version keeps the latest real date. Equal timestamps for one contact need a tiebreaker column in the sort, or a stable sort, to make the survivor repeatable. Add `ignore_index=True` if downstream code expects labels 0 to n-1.

code

python · 21 lines
python
import pandas as pd

crm = pd.DataFrame({
    "contact_id": [101, 102, 101, 103, 102, 101],
    "signup": pd.to_datetime(["2026-01-05", "2026-02-01", "2026-03-10",
                              "2026-03-11", "2026-01-20", None]),
    "plan": ["free", "pro", "pro", "free", "free", "trial"],
})

naive = crm.sort_values("signup").drop_duplicates("contact_id", keep="last")
print(naive.loc[naive["contact_id"] == 101, "plan"].item())   # trial (the NaT row)

latest = (crm.sort_values("signup", ascending=False)
             .drop_duplicates("contact_id", ignore_index=True))
print(latest)
#    contact_id     signup  plan
# 0         103 2026-03-11  free
# 1         101 2026-03-10   pro
# 2         102 2026-02-01   pro

assert latest["contact_id"].is_unique

go deeper

for a junior

Recall that keep refers to row position, so the frame must be sorted by date before drop_duplicates on the contact key.

for a middle

Explain why the two sort directions diverge when dates are missing, and why ignore_index and a tiebreaker matter.

for a senior

Show that you assert uniqueness after the dedupe, count missing dates first, and make tied timestamps resolve the same way on every run.

for a principal

Weigh where the keep-latest rule should live in a team's pipelines, so one documented survivor policy replaces ad hoc sort-and-drop calls.

## The problem in pandas terms A CRM export often lists the same contact once per sign-up: a free trial in January, a paid plan in March, a re-activation in April. You want one row per `contact_id`, the most recent one. pandas has no "keep the newest" switch, because `DataFrame.drop_duplicates` decides which copy survives purely by **row position**: - `keep='first'` (the default) keeps the copy that appears earliest in the frame; - `keep='last'` keeps the copy that appears latest; - `keep=False` drops every copy, which removes the contact entirely. So "most recent" has to be turned into "first" or "last" by **sorting before deduplicating**. Sorting is its own lesson; here it is one step of the recipe. ## The two-step recipe 1. Sort by the date column so that each contact's rows are in date order: `crm.sort_values('signup')`. 2. Deduplicate on the contact key and keep the end of each run that holds the newest date: `.drop_duplicates('contact_id', keep='last')`. Or the mirror image: sort descending and keep the default first copy, `crm.sort_values('signup', ascending=False).drop_duplicates('contact_id')`. The `subset` argument, here the positional `'contact_id'`, is what makes this a per-contact dedupe. Without it pandas compares all columns, and two sign-ups with different dates are never duplicates, so nothing would be removed. ## Where the two idioms differ: missing dates `sort_values` has `na_position='last'` as its default, and that default holds **in both directions**. A row whose `signup` is `NaT` (pandas' missing datetime) therefore sorts to the end whether you sort ascending or descending. | Idiom | Where a `NaT` row lands | Survivor for a contact with an undated row | |---|---|---| | `sort_values('signup')` then `keep='last'` | after all real dates | the undated row | | `sort_values('signup', ascending=False)` then `keep='first'` | after all real dates | the latest real date | | either sort with `na_position='first'`, then `keep='last'` | before all real dates | the latest real date | The ascending version silently promotes an undated row to "latest". Decide explicitly how undated rows should rank, and check with `crm['signup'].isna().sum()` before trusting either idiom. ## Tracing one contact Take contact 101 with three rows: a free plan on 2026-01-05, a pro plan on 2026-03-10, and a trial row with no date. 1. `sort_values('signup')` orders them 2026-01-05, 2026-03-10, `NaT`. 2. `drop_duplicates('contact_id', keep='last')` keeps the last of the three, the undated trial row. 3. `sort_values('signup', ascending=False)` orders them 2026-03-10, 2026-01-05, `NaT`. 4. `drop_duplicates('contact_id')` keeps the first of the three, the pro plan from March. Both recipes look equivalent in code review, and on a clean extract they return the same rows. The difference appears only on the day the export carries a missing date, which is exactly when nobody is watching. ## Ties and labels - **Equal timestamps.** Two sign-ups for one contact at the same moment leave the sort to decide their order. The default `kind='quicksort'` for a single sort key is not stable, so add a tiebreaker such as `sort_values(['signup', 'signup_seq'])` or pass `kind='stable'` to keep file order. - **Labels.** The survivors keep their original index labels, in sorted order, so the index is shuffled and gappy. `ignore_index=True` on `drop_duplicates` relabels them 0 to n-1. - **Row order.** The result stays in date order. Sort it again by `contact_id` if a report expects that. ## Checking the result A dedupe that should leave one row per contact can be asserted: - `latest['contact_id'].is_unique` should be `True`; - `len(latest)` should equal `crm['contact_id'].nunique()`; - `crm.duplicated('contact_id').sum()` tells you how many rows were removed. These checks catch a forgotten `subset`, which leaves duplicates in place, and a wrong key column. ## Which record should win Whether "latest" is even the right survivor, and whether some fields should be merged from older rows, is a data decision that the library-neutral material on combining tables covers. pandas only executes the rule you encode with the sort order and `keep`. Encode it in one place, with a comment, so the next person can see which copy wins and why.

  • Why does crm.drop_duplicates(keep='last') with no subset leave every contact's rows in place?
    Without `subset`, pandas compares all columns. Two sign-ups for one contact differ at least in their date, so no row is an exact copy of another and nothing is removed. Pass `subset='contact_id'`, or the list of columns that identify a contact.
  • After the dedupe, how do you confirm exactly one row per contact remains?
    Assert `latest['contact_id'].is_unique` and compare `len(latest)` with `crm['contact_id'].nunique()`. Both catch a wrong or missing `subset`, and the second also catches a contact lost entirely, for example by `keep=False`.
  • What happens if you use keep=False in this recipe?
    Every contact that appears more than once is removed completely, so only contacts with a single sign-up remain. That is useful for listing clean, unrepeated contacts, but it is the opposite of keeping the latest record.

Think of a pile of dated forms per customer: drop_duplicates only takes the top or bottom form of each pile, so you must first stack each pile by date, and decide where undated forms go.

  • drop_duplicates with keep='last' picks the row with the newest date automatically
  • Sorting ascending with keep='last' and descending with keep='first' always give the same rows
  • Missing dates sort first when you sort descending
  • drop_duplicates without subset deduplicates on the first column
  • ignore_index=True makes the index part of the duplicate comparison