Data Science · Level 3 Cleaning

Removing Duplicates in pandas

A newsletter export lists some people twice. Keep each email's latest sign-up with drop_duplicates(subset, keep="last").

  • drop_duplicates() removes repeats
  • subset= compares chosen columns
  • keep="first" or keep="last"

drop_duplicates() removes repeated rows. Trap: by default a row counts as a duplicate only if every column matches. Pass subset=["email"] to compare one column, and keep="last" to keep the latest row.

s = pd.DataFrame({"email": ["[email protected]", "[email protected]"], "plan": ["free", "pro"]})
len(s.drop_duplicates())   # 2: the plans differ
s.drop_duplicates(subset=["email"], keep="last")["plan"].tolist()   # ['pro']

Write latest_signups(df) that keeps only the last row of each email (the file is in date order) and returns it with a fresh index, for example two rows for [email protected] keep the second one.

solution.py
Test Suites Pending
Output