Sub topic 13
Normalizing values before deduplicating
This chapter assumes you know duplicated(), drop_duplicates() with subset and keep, and the .str accessor from the earlier chapters.
Why exact matching misses duplicates
duplicated() compares values exactly. The strings "[email protected]" and "[email protected] " differ in case and in a trailing space, so pandas treats them as different values. A deduplication step that looks correct can leave near-duplicates behind.
Normalizing means converting values to one canonical form before you compare them. The usual fixes are:
| Problem | Typical fix |
|---|---|
| Leading or trailing spaces | `.str.strip()` |
| Mixed capitalization | `.str.lower()` |
| Repeated inner spaces | `.str.replace(r"\s+", " ", regex=True)` |
| Numbers stored as text | `pd.to_numeric(..., errors="coerce")` |
Use a temporary key column
Overwriting the original column loses information, such as the capitalization the user typed. A safer pattern is to build a normalized key, deduplicate on that key, and then drop it.
import pandas as pd
customers = pd.DataFrame({
"email": ["[email protected]", "[email protected] ", "[email protected]"],
"city": ["Oslo", "Oslo", "Rome"],
})
print(customers["email"].duplicated().sum()) # 0
customers["email_key"] = customers["email"].str.strip().str.lower()
print(customers["email_key"].duplicated().sum()) # 1
clean = (
customers.drop_duplicates(subset="email_key", keep="first", ignore_index=True)
.drop(columns="email_key")
)
print(clean["email"].tolist()) # ['[email protected]', '[email protected]']The first check finds no duplicates, because the raw strings all differ. The second check finds one, because two keys are now identical. With keep="first", the row with the original "[email protected]" survives.
Combine this with keep-latest
The normalized key works with the earlier keep-latest pattern. Sort by the date column first, then call drop_duplicates(subset="email_key", keep="last"). Normalization decides which rows count as the same record. Sorting decides which of those rows wins.
Gotchas
- Missing values pass through
.strmethods asNaN.duplicated()treatsNaNvalues as equal to each other, so rows with a missing key collapse into one. Filter them out first withdropna(subset=["email_key"])if that is not what you want. - Normalize only what the business rule allows. Lowercasing is safe for email addresses but wrong for case-sensitive identifiers such as product codes.
- A key built from several columns needs each part normalized. For example, you can join the stripped, lowercased parts with
"|"and use that as the key. You can also pass several normalized columns tosubset. .strmethods returnNaNfor non-string values. If a column mixes numbers and text, convert it withastype("string")first.
Verify the result
Compare counts before and after. Here the row count should drop by exactly the number of flagged duplicates.
before = len(customers)
flagged = customers["email_key"].duplicated().sum()
after = len(clean)
assert before - flagged == after
print(before, flagged, after) # 3 1 2If the numbers disagree, print the rows where the key is duplicated with keep=False. Then check whether your normalization missed a variation.
Exercise
A DataFrame has a name column with the values " Li Wei", "li wei" and "Li Wei". Which .str steps produce one shared key, and how many rows does drop_duplicates(subset="key") keep?
Show answer
Chain .str.strip().str.lower().str.replace(r"\s+", " ", regex=True). All three values become "li wei", so drop_duplicates(subset="key") keeps one row.