Deduplicate DataFrame Rows by Email, Keeping the First Occurrence
Quick Overview
Write a pandas function that removes rows whose email already appeared earlier in a DataFrame, keeping the first occurrence, all columns and a fresh index. It tests drop_duplicates with a column subset, which row survives, and how exact matching treats case and missing values.
Deduplicate DataFrame Rows by Email, Keeping the First Occurrence
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `dedup_by_email(df)`, where `df` has columns `['email', 'name', 'signup_day']`. Remove any row whose `email` appeared in an earlier row, keeping the first occurrence.
The function must meet these requirements:
- Drop duplicates on `subset=['email']` with `keep='first'`.
- Keep all columns and the relative order of surviving rows.
- Return a fresh `0..n-1` index (`ignore_index=True`).
For example:
```python
df = pd.DataFrame({
'email': ['a@x.com', 'b@x.com', 'a@x.com'],
'name': ['Ann', 'Bob', 'Andy'],
'signup_day': [1, 2, 3],
})
dedup_by_email(df)
# email name signup_day
# 0 a@x.com Ann 1
# 1 b@x.com Bob 2
```
Row 2 repeats `a@x.com` from row 0, so it is dropped, and the two surviving rows are numbered 0 and 1.
```hint Which row survives
Look at how `drop_duplicates` compares rows when you pass `subset`, which copy `keep` retains, and what happens to the index once rows are removed.
```
### Constraints & Assumptions
- Emails are compared exactly as stored, with no trimming or case folding.
- "Earlier" refers to row order in `df`, not to `signup_day`.
### What a Strong Answer Covers
- Deduplicating on `email` alone while keeping every column.
- Which row survives for a repeated email, and why the survivors keep their relative order.
- Producing a fresh 0 to n-1 index.
- How exact matching treats case, whitespace and missing emails.
### Follow-up Questions
- How would you keep the row with the earliest `signup_day` when the input is not sorted by it?
- How would you treat `A@x.com` and `a@x.com` as the same email?
- How would you report how many rows each email had before removing the duplicates?
Overview: Write a pandas function that removes rows whose email already appeared earlier in a DataFrame, keeping the first occurrence, all columns and a fresh index. It tests drop_duplicates with a column subset, which row survives, and how exact matching treats case and missing values.
Implement dedup_by_email(df), where df has columns ['email', 'name', 'signup_day']. Remove any row whose email appeared in an earlier row, keeping the first occurrence.
The function must meet these requirements:
Drop duplicates on
subset=['email']
with
keep='first'
.
Keep all columns and the relative order of surviving rows.
Return a fresh
0..n-1
index (
ignore_index=True
).