Sub topic 15
Verifying the result
This chapter assumes you can run rename() and drop_duplicates() as covered earlier. It shows how to confirm that each step did what you intended before you rely on the data.
Why verify
Both operations can fail without raising an error. rename() ignores keys that match nothing, and drop_duplicates() removes any rows that match on the columns you chose. A wrong subset or a typo in a mapping gives you a DataFrame that looks fine and holds the wrong data. A few cheap checks catch most of these problems.
Check the labels after a rename
Compare the full label list with what you expect. This catches mapping keys that silently matched nothing, such as a trailing space in "Customer Name ". Also check that the labels are unique, because two columns can end up with the same name after a bulk cleanup.
Check the counts after deduplicating
Record the row count and the number of flagged duplicates before you drop anything. Afterward, the new length must equal the old length minus the flagged count. With subset, duplicated() and drop_duplicates() must use the same subset and keep arguments, or the numbers will not match.
Then confirm that no duplicates remain, and that the index is what you expect.
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],
})
df = raw.rename(columns={
"Order ID": "order_id",
"Customer Name": "customer",
"Total $": "total",
})
# Labels: exact list and no repeats
assert df.columns.tolist() == ["order_id", "customer", "total"]
assert df.columns.is_unique
# Rows: counts before and after
before = len(df)
flagged = df.duplicated().sum()
clean = df.drop_duplicates(ignore_index=True)
assert len(clean) == before - flagged
assert not clean.duplicated().any()
assert clean.index.equals(pd.RangeIndex(len(clean)))
assert clean["order_id"].is_unique
print(before, "->", len(clean), "rows;", flagged, "duplicate removed")
print(clean.shape)The script prints 4 -> 3 rows; 1 duplicate removed and then (3, 3). If any assertion fails, Python raises AssertionError and stops the script, which is what you want in a cleanup pipeline.
Inspect before you trust a subset
When you deduplicate on a subset, the rows you drop can differ in the other columns. Look at them first. Passing keep=False marks every member of each duplicate group, not just the repeats, so you see everything involved.
import pandas as pd
events = pd.DataFrame({
"user": ["a", "a", "b"],
"plan": ["free", "pro", "free"],
})
group = events[events.duplicated(subset="user", keep=False)]
print(group)This prints both rows for user a. They disagree on plan, so you must decide which one wins. Sort first and use keep="last" if the newest row should win.
What to check, and what it tells you
| Check | Expression | A failure means |
|---|---|---|
| Labels match | `df.columns.tolist() == expected` | A mapping key matched nothing, or a label was misspelled |
| Labels unique | `df.columns.is_unique` | Two columns share a name |
| Row count | `len(clean) == before - flagged` | `subset` or `keep` differ between the two calls |
| No repeats left | `not clean.duplicated().any()` | The `subset` was narrower than the check |
| Key unique | `clean["id"].is_unique` | The deduplication key does not identify a row |
Exercise
A DataFrame df has 1,000 rows. df.duplicated(subset="email").sum() returns 40, but after clean = df.drop_duplicates() the length is 1,000. What went wrong, and how do you fix it?
Show answer
drop_duplicates() was called without subset="email", so it compared whole rows. Rows with the same email but different values in other columns were not duplicates under that rule. Call df.drop_duplicates(subset="email") with the same subset as the check, and the length should be 960.
Exercise
Write one assertion that confirms clean has no repeated values in a key column named order_id.
Show answer
assert clean["order_id"].is_unique