skip to content

Before deleting repeated contacts in pandas, how does duplicated(keep=False) let you inspect every copy, and why is the default keep misleading for review?

level: seniorimportance: should knowfreq 44%

answer

  1. the default hides the original
  2. flag the whole group
  3. sort to put copies together
  4. two sums, two meanings
  5. missing keys form one group

basics

~10 s

duplicated(keep=False) flags every row in a duplicate group, originals included, so df[mask].sort_values(key) shows each group side by side. The default keep='first' flags only later copies, leaving nothing to compare them with.

solid answer

~40 s

With the default `keep='first'`, `df[df.duplicated('contact_id')]` lists only the second and later copies, so a reviewer sees orphans without the record they repeat. `df.duplicated('contact_id', keep=False)` marks every member of every duplicate group; filtering with it and sorting by the key, then by date, puts each group's rows together so you can see which columns actually conflict. The two sums answer different questions: `duplicated().sum()` is how many rows a dedupe would remove, `duplicated(keep=False).sum()` is how many rows take part. Before trusting the groups, check two pandas behaviours: missing keys compare equal, so all rows with no email form one giant group, and comparison is exact, so case and spacing variants slip through until you normalise the key.

code

python · 17 lines
python
import pandas as pd

crm = pd.DataFrame({
    "contact_id": [101, 102, 101, 103, 102, 101],
    "email": ["[email protected]", "[email protected]", "[email protected] ", None, "[email protected]", None],
    "plan": ["free", "pro", "pro", "free", "free", "trial"],
})

print(crm.duplicated("contact_id").sum())              # 3 rows would be removed
print(crm.duplicated("contact_id", keep=False).sum())  # 5 rows are involved

print(crm.duplicated("email", keep=False).tolist())
# [False, True, False, True, True, True]  rows 3 and 5 match only on a missing email

key = crm["email"].str.strip().str.lower()
mask = key.notna() & key.duplicated(keep=False)
print(crm[mask].sort_values("contact_id").index.tolist())  # [0, 2, 1, 4]

go deeper

for a junior

Recall that keep=False flags every copy in a group, while the default flags only the copies after the first.

for a middle

Explain the difference between the two sums and why sorting the flagged rows by key makes a review readable.

for a senior

Demonstrate excluding missing keys, normalising text keys and separating exact copies from key-only conflicts before any rows are dropped.

for a principal

Argue for a standard duplicate report, counts plus sampled groups, that every ingestion job emits before a dedupe is allowed to run.

## Why the default is the wrong lens `DataFrame.duplicated(subset=None, keep='first')` returns a boolean Series, one value per row. With the default `keep='first'`, the first copy of each group is marked `False` and only the later copies `True`. That is exactly right for **removing** duplicates, and wrong for **reviewing** them: - `crm[crm.duplicated('contact_id')]` shows the copies that would be dropped, but not the copy that would stay; - a reviewer cannot see what differs between the kept and dropped rows; - a group of three shows up as two rows, which understates how messy that contact is. ## keep=False flags the whole group Passing `keep=False` marks **every** row whose key occurs more than once, the first copy included: ```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", "2026-04-01"]), "plan": ["free", "pro", "pro", "free", "free", "trial"], }) mask = crm.duplicated("contact_id", keep=False) review = crm[mask].sort_values(["contact_id", "signup"]) ``` `review` holds all five rows of contacts 101 and 102, grouped by contact and in date order, while contact 103, which appears once, is left out. Sorting by the key is what makes the groups readable: the mask preserves the frame's original order, where copies may sit thousands of rows apart. ## Reading the numbers Three counts describe the duplication, and they are easy to confuse: | Expression | Value here | Meaning | |---|---|---| | `crm.duplicated('contact_id').sum()` | 3 | rows a default dedupe would remove | | `crm.duplicated('contact_id', keep=False).sum()` | 5 | rows that belong to some duplicate group | | `crm.loc[mask, 'contact_id'].nunique()` | 2 | contacts that are duplicated | The second sum minus the first, 5 - 3 = 2, equals the number of duplicate groups, because each group leaves exactly one first copy unflagged under the default. A quick per-key view is `crm['contact_id'].value_counts().loc[lambda s: s > 1]`, which lists each repeated key with its count. ## How big are the groups? A review usually wants the shape of the problem before the details. Counting the counts gives it in one line: ```python # continuing with the crm frame defined above sizes = crm["contact_id"].value_counts() sizes.value_counts() # 3 -> 1 contact, 2 -> 1 contact, 1 -> 1 contact ``` The outer `value_counts` runs on the per-contact counts, so its index is a group size and its value is how many contacts have that size. A long tail of contacts with 20 or 50 copies usually means a broken join or a retrying export job upstream, not customers signing up again, and those groups deserve a look before any dedupe rule is applied to them. ## Two traps before you trust the groups 1. **Missing keys form one group.** Duplicate detection treats missing values as equal, so every row with no email is flagged as a copy of every other. Restrict the check first, for example `has_email = crm['email'].notna()` and `crm[has_email & crm.duplicated('email', keep=False)]`, and handle undated or unkeyed rows separately. 2. **Exact comparison misses near-duplicates.** `'[email protected]'`, `'[email protected]'` and `'[email protected] '` are three distinct values. Build a normalised key with `str.strip()` and `str.lower()`, then run `duplicated` on that column; the text methods themselves are covered with text columns. ## Exact copies versus key-only copies Comparing two masks tells you what kind of duplication you have: - `crm.duplicated(keep=False)` with no `subset` flags rows identical in **every** column, which are safe to collapse; - `crm.duplicated('contact_id', keep=False)` flags rows sharing the **key**, which may disagree on plan, date or address. Rows in the second mask but not the first carry conflicting attributes, and those are the ones that need a survivor rule. Which record should survive is a modelling decision covered with combining tables; pandas' job is to show you the conflict before you encode the rule. ## Duplicate labels are a separate check `duplicated` ignores the index. If the row labels themselves should be unique, check `crm.index.is_unique` or `crm.index.duplicated(keep=False)`, which returns a NumPy boolean array you can use as a mask. What duplicate labels do to selection and reindexing is covered with axis labels. ## A review routine - Count with both sums and log them. - Exclude missing keys, normalise text keys. - Inspect `crm[mask].sort_values([key, date])` for a sample of groups. - Separate exact copies from key-only copies. - Only then call `drop_duplicates` with the rule you settled on, and assert the key is unique afterwards.

  • How do you list each repeated contact with how many times it occurs?
    `crm['contact_id'].value_counts().loc[lambda s: s > 1]` returns one row per repeated key with its count, sorted from most to least frequent. It complements the `keep=False` mask, which shows the rows themselves.
  • How do you tell exact copies from rows that only share a contact key?
    Compare `crm.duplicated(keep=False)`, which needs every column equal, with `crm.duplicated('contact_id', keep=False)`. Rows flagged by the key mask but not the all-columns mask disagree somewhere, so they need a survivor rule rather than a blind dedupe.

  • df[df.duplicated('id')] shows every copy of each repeated id
  • duplicated().sum() is the number of rows involved in duplication
  • Rows with a missing key are ignored by duplicated
  • keep=False keeps every copy of each duplicated row
  • duplicated matches '[email protected]' and '[email protected]' as the same value