Sub topic 15
Verifying the result
A cleanup step that runs without an error has not necessarily done what you intended. rename() ignores keys that match nothing, and drop_duplicates() removes whatever it considers a duplicate, which may not be what you meant. This chapter covers checks you can run after each step.
It assumes you know how to use rename(), assign to df.columns, and call duplicated() and drop_duplicates() with subset, keep, and ignore_index. It also assumes you can read a basic assert statement.
What to check
Each kind of cleanup fails in its own way, so each needs its own checks.
| Step | What can go wrong | Check |
|---|---|---|
| Rename | A key is misspelled and silently ignored | Compare mapping keys with `df.columns` |
| Rename | Two columns end up with the same label | `df.columns.is_unique` |
| Rename | The result is not assigned | Inspect `df.columns.tolist()` |
| Dedup | The wrong columns define a duplicate | Compare the row count with `duplicated(subset=...).sum()` |
| Dedup | The wrong row survives | Compare against an independent computation |
| Dedup | The index has gaps | Compare it with `RangeIndex` |
Verifying a rename
Check the mapping before you apply it. rename() ignores unmatched keys by default, so a typo like "Customer name" produces no error and no change.
import pandas as pd
raw = pd.DataFrame({
"Order ID": [1, 2, 2, 3],
"Customer Name": ["Ann", "Bob", "Bob", "Cy"],
"Total $": [10.0, 20.0, 20.0, 5.0],
})
mapping = {"Order ID": "order_id", "Customer Name": "customer", "Total $": "total"}
missing = set(mapping) - set(raw.columns)
assert not missing, f"keys not found: {missing}"
clean = raw.rename(columns=mapping)
assert clean.columns.tolist() == ["order_id", "customer", "total"]
assert clean.columns.is_unique
assert clean.shape == raw.shape
assert raw.columns.tolist() == ["Order ID", "Customer Name", "Total $"]
print("rename ok")The last assertion confirms that raw was not modified. rename() returns a new DataFrame, so a forgotten assignment leaves the old labels in the variable you keep using. Checking clean.columns rather than the call itself catches that mistake.
Passing errors="raise" does the same key check inside pandas. The explicit set difference is still useful because it lets you print every missing key at once.
Collisions create duplicate labels
Renaming does not stop you from giving two columns the same label.
import pandas as pd
df = pd.DataFrame({"a": [1], "b": [2]})
out = df.rename(columns={"b": "a"})
print(out.columns.tolist()) # ['a', 'a']
print(out.columns.is_unique) # FalseThe same thing can happen with bulk cleanup. The labels "Total $" and "Total %" both become "total" under the regular expression from earlier chapters. Run is_unique after any bulk rename. If it returns False, find the offenders with out.columns[out.columns.duplicated()].
Verifying deduplication
After drop_duplicates(), the number of rows removed should equal the number of rows duplicated() flagged. This holds for keep="first" and keep="last", because both keep exactly one row from each group. Compute the expected count before you drop anything, then compare.
before = len(clean)
flagged = int(clean.duplicated().sum())
deduped = clean.drop_duplicates(ignore_index=True)
after = len(deduped)
assert before - after == flagged
assert not deduped.duplicated().any()
assert deduped.index.equals(pd.RangeIndex(len(deduped)))
assert deduped.columns.equals(clean.columns)
print(before, after, flagged) # 4 3 1Each assertion covers a separate failure:
- The count check shows that exactly the flagged rows were removed.
not deduped.duplicated().any()shows that no duplicates remain.- The index check applies only when you passed
ignore_index=True. Without it, gaps in the index are expected. - The column check confirms that the columns are unchanged.
With keep=False the counts differ
keep=False removes every member of a duplicated group, including the first. The expected removal count is then duplicated(keep=False).sum(), not duplicated().sum(). Using the wrong one makes a correct result look broken.
Verifying a subset deduplication
When you deduplicate on a key, the checks should say something about that key. The result must have a unique key, and no key may have disappeared.
import pandas as pd
events = pd.DataFrame({
"user": ["a", "a", "b"],
"updated": ["2026-01-01", "2026-02-01", "2026-01-15"],
"plan": ["free", "pro", "free"],
})
latest = (
events.sort_values("updated")
.drop_duplicates(subset="user", keep="last")
)
assert latest["user"].is_unique
assert set(latest["user"]) == set(events["user"])
expected = events.groupby("user")["updated"].max()
assert latest.set_index("user")["updated"].to_dict() == expected.to_dict()
print("latest ok")The final assertion is the important one. The first two would pass even if the wrong row survived, for example after a missing sort_values(). The groupby computation reaches the same answer by a different route, so agreement between the two is real evidence. Comparing with to_dict() ignores row order, which differs here because the result is sorted by date and the groupby output is sorted by user.
The sort in this example works because the dates are ISO-formatted strings, which sort correctly as text. If your dates are in another format, convert them with pd.to_datetime() first, and check the dtype before you trust the sort.
A reusable check
If you deduplicate in several places, put the counting logic in one function. It returns the numbers so you can log them, and it raises when they disagree.
import pandas as pd
def check_dedup(before, after, subset=None):
removed = len(before) - len(after)
expected = int(before.duplicated(subset=subset).sum())
if removed != expected:
raise AssertionError(f"removed {removed} rows, expected {expected}")
if after.duplicated(subset=subset).any():
raise AssertionError("duplicates remain")
return {"rows_before": len(before), "rows_after": len(after), "removed": removed}
df = pd.DataFrame({"k": [1, 1, 2], "v": ["x", "y", "z"]})
result = df.drop_duplicates(subset="k")
print(check_dedup(df, result, subset="k"))
# {'rows_before': 3, 'rows_after': 2, 'removed': 1}This function assumes keep="first" or keep="last". For keep=False, pass the expected count in separately.
Edge cases that fool the checks
- Missing values.
duplicated()treats twoNaNvalues in the same column as equal. Two rows that differ only by missing data in the same place are counted as duplicates. This is usually what you want, but confirm it when missing values mean "unknown" rather than "empty". - Near-duplicates.
"Ann"and"ann "are different strings, so a clean count of zero remaining duplicates proves nothing about them. Normalize first with.str.strip().str.lower(), then count again. If the count rises after normalization, the earlier pass missed rows. - Dtype differences. The integer
1and the string"1"never match. A key column read from a CSV in one place and built in code in another can quietly defeat the dedup. Printdf.dtypesalongside your counts. - Subset columns that do not exist.
drop_duplicates(subset="usr")raises aKeyError, which is helpful. The risk is picking the wrong existing column, so write down which columns make up the key.
Summary of habits
- Check the mapping keys before renaming, and
is_uniqueafter. - Compare labels with an explicit list, not by eye.
- Compute the expected removal count before dropping rows.
- Assert that no duplicates remain under the same
subsetyou used. - For "keep the latest" logic, verify against a
groupbyresult.
Exercise
A DataFrame has 100 rows. df.duplicated(subset="id").sum() returns 12. You run out = df.drop_duplicates(subset="id", keep=False). How many rows would you expect in out if every duplicated id appears exactly twice, and which count should your check use instead?
Show answer
Twelve rows are flagged as repeats, so twelve ids appear twice, which means 24 rows belong to duplicated groups. keep=False removes all of them, so out has 100 - 24 = 76 rows. The check must use df.duplicated(subset="id", keep=False).sum(), which returns 24, instead of the default count of 12.
Exercise
You run df.rename(columns={"Total $": "total", "Total %": "total"}) and then df["total"].sum() fails in an unexpected way. Which one-line check would have caught the problem right after the rename, and why does the failure happen?
Show answer
assert out.columns.is_unique would have caught it. Both columns were renamed to "total", so the label is duplicated and out["total"] returns a DataFrame with two columns instead of a Series. Operations that expect a single column then behave differently or fail.