Sub topic 13
Normalizing values before deduplicating
This chapter assumes you can already use duplicated() and drop_duplicates() with subset and keep. It also assumes you are comfortable with the .str accessor from the label-cleaning chapters. Here you will see why exact comparison misses duplicates that a person would spot at once, and how to fix the values first.
Why exact matching misses duplicates
duplicated() and drop_duplicates() compare values exactly. Two cells match only if they are equal, so "[email protected]" and "[email protected] " are different values. A trailing space or a different letter case is enough to hide a duplicate.
import pandas as pd
df = pd.DataFrame({
"email": ["[email protected]", "[email protected] ", "[email protected]", "[email protected]"],
"city": ["Oslo", "Oslo", "Rome", "Rome"],
})
print(df.duplicated().sum()) # 0A person reads this table as two customers, each entered twice. pandas reports zero duplicates. The fix is to normalize the values first, then deduplicate.
df["email"] = df["email"].str.strip().str.lower()
print(df.duplicated().sum()) # 2
clean = df.drop_duplicates(ignore_index=True)
print(clean.shape) # (2, 2)Deduplication did not change. The data did. This is the whole idea of the chapter: make equivalent values identical, then let drop_duplicates() do its normal job.
The order of operations
Normalization always comes before the duplicate check. Checking the result afterwards also tells you how much the normalization found.
Count before you drop. If duplicated().sum() is far larger than you expected, your normalization may be too aggressive and is merging values that are really different.
Common normalizations by data type
Each kind of column has its own typical sources of false differences.
| Column holds | Typical problem | Normalization |
|---|---|---|
| Emails, usernames | Case, stray spaces | `.str.strip().str.lower()` |
| Names | Repeated inner spaces, case | `.str.lower()` and `.str.replace(r"\s+", " ", regex=True)` |
| Phone numbers | Punctuation, spaces | `.str.replace(r"\D", "", regex=True)` |
| Text with accents | Same character stored in different Unicode forms | `.str.normalize("NFKC")` |
| Prices, measurements | Floating-point noise | `.round(2)` |
| Dates stored as text | Mixed formats | `pd.to_datetime(...)` |
| Numbers stored as text | `"1"` versus `1` | `pd.to_numeric(...)` |
Apply only what the column needs. A rule that is right for emails can be wrong for another column. Lowercasing a product code like "aB-12" could merge two items that really are different.
Normalizing without overwriting the original
Overwriting a column, as in the first example, loses the original text. Sometimes you must keep it, for example a customer name that is printed on an invoice. In that case, build a separate key and deduplicate by the key.
import pandas as pd
customers = pd.DataFrame({
"name": ["Ann Lee", "ann lee", "Bob Ray"],
"phone": ["555-0100", "(555) 0100", "555-0199"],
})
keys = pd.DataFrame({
"name": (
customers["name"]
.str.lower()
.str.replace(r"\s+", " ", regex=True)
.str.strip()
),
"phone": customers["phone"].str.replace(r"\D", "", regex=True),
})
mask = ~keys.duplicated()
result = customers[mask]
print(result["name"].tolist()) # ['Ann Lee', 'Bob Ray']keys holds the normalized copy. keys.duplicated() flags the second row, and ~ inverts the flags so True means "keep". Indexing customers with the mask keeps the original spelling of the first occurrence. The mask lines up with customers by index label, so both frames must share the same index. Here they do, because keys was built from columns of customers.
You could also add the key as a helper column, call drop_duplicates(subset="key"), and then drop the helper column. The mask approach avoids touching the original frame at all.
What pandas already treats as equal
Some values you might expect to need cleanup are already handled.
Missing values compare equal to each other in duplicated(). Two rows that both have NaN in a column count as matching in that column.
import pandas as pd
df = pd.DataFrame({"a": [None, None], "b": [1, 1]})
print(df.duplicated().tolist()) # [False, True]This is different from ordinary comparison, where NaN == NaN is False. If you do not want missing values to match, fill them with distinct values or drop those rows before deduplicating.
Integers and floats with the same numeric value also compare equal. Strings and numbers do not: "1" and 1 are different, so convert the column to one type first.
Floating-point noise
Numbers computed by arithmetic can differ in the last binary digits even when they look the same after printing.
import pandas as pd
prices = pd.Series([0.1 + 0.2, 0.3])
print(prices.duplicated().tolist()) # [False, False]
print(prices.round(2).duplicated().tolist()) # [False, True]0.1 + 0.2 is stored as 0.30000000000000004, which is not equal to 0.3. Rounding to the precision that matters for your data makes them equal. Choose the number of decimals from the real meaning of the column. Rounding currency to cents is reasonable. Rounding a sensor reading to cents may erase real differences.
Dates and types
Dates written as text often hide duplicates because the same day appears in several formats. Convert them to real datetimes, giving the format explicitly when you know it, so that a day like 01/05/2026 is not read two different ways.
import pandas as pd
events = pd.DataFrame({"when": ["2026-01-05", "2026-01-05", "2026-01-06"]})
events["when"] = pd.to_datetime(events["when"], format="%Y-%m-%d")
print(events.duplicated().sum()) # 1
print(events["when"].dtype) # datetime64[ns]If a column contains several formats, convert each format separately with its own format= value. Guessing a format for ambiguous dates such as 01/05/2026 can silently swap day and month, which creates false matches and false differences.
Pitfalls
- Over-normalizing. Stripping all non-digits from an identifier column can merge
"AB-12"and"12". Normalize only as far as the real-world meaning allows. - Forgetting to assign. String methods return new objects.
df["email"].str.lower()on its own changes nothing indf. - Normalizing only some key columns. If
subset=["email", "city"]is your key, both columns need cleanup. A clean email next to a messy city still hides duplicates. - Missing the
.straccessor on non-string data. A column of mixed types with numbers in it givesNaNfor those entries when you use.strmethods. Convert withastype("string")first when you need every value treated as text. - Checking only the count. A drop in row count tells you rows were removed, not that the right rows were removed. Inspect a few removed rows.
To see which rows were removed, flag all members of each duplicate group with keep=False:
import pandas as pd
df = pd.DataFrame({
"email": ["[email protected]", "[email protected] ", "[email protected]"],
})
df["email"] = df["email"].str.strip().str.lower()
group = df[df.duplicated(keep=False)]
print(group["email"].tolist()) # ['[email protected]', '[email protected]']keep=False marks every row in a repeated group, including the first one. This lets you review the merged records side by side before you delete anything.
Verifying the result
After normalizing and dropping, compare before and after:
- Record
len(df)anddf.duplicated(subset=key).sum()before the change. - Normalize and run
drop_duplicates(subset=key). - Check that
len(result)equals the old length minus the old duplicate count, and thatresult.duplicated(subset=key).sum()is0.
Because normalization can create new matches, the duplicate count measured before normalizing is not the one to compare against. Measure it after normalizing and before dropping.
Exercise
A DataFrame has an email column with values "[email protected]", "[email protected] " and "[email protected]". Calling df.drop_duplicates(subset="email") removes nothing. Write the steps that make it remove one row, and say what df.duplicated(subset="email").sum() returns before and after normalizing.
Show answer
Normalize first with df["email"] = df["email"].str.strip().str.lower(), then call df.drop_duplicates(subset="email"). The first two values become "[email protected]" and match. Before normalizing, the sum is 0, because all three strings differ exactly. After normalizing, the sum is 1, and the drop leaves two rows.
Exercise
You must keep customer names exactly as typed, but you want to remove rows whose names match after ignoring case and repeated spaces. How do you do it without changing the name column?
Show answer
Build a normalized key, for example key = df["name"].str.lower().str.replace(r"\s+", " ", regex=True).str.strip(). Then keep rows with df[~key.duplicated()]. The mask removes the later matches and the name column keeps its original text.