Sub topic 7
Cleaning with named, re-runnable steps
Prerequisites
This chapter assumes you can write Python functions and use pandas filtering and string methods. It also assumes you have already loaded raw data into df_raw and audited it with a quality report, as in the previous chapters. Here you turn the audit's findings into code that anyone can re-run and review.
Why cleaning needs structure
Cleaning is where an analysis changes the data, so every decision there can change a later result. If you drop rows in one cell, overwrite a column in another, and fix a typo by hand in a third, you cannot say what produced the final table. Re-running the notebook from the top may give a different answer.
Three habits prevent this:
- Each rule is a named function that takes a DataFrame and returns a new one.
- The raw DataFrame is never modified.
- Every step reports how many rows it removed.
A cleaning step then reads as a decision you can inspect, argue with, and change.
A single cleaning function
The simplest version puts all rules in one function. It starts by copying, so the caller's DataFrame is untouched.
def clean_orders(df):
out = df.drop_duplicates().copy()
out["region"] = out["region"].str.strip().str.lower()
out = out[out["amount"].notna() & (out["amount"] >= 0)]
return out
df = clean_orders(df_raw)
print(f"rows kept: {len(df)} of {len(df_raw)}")Four details matter here:
drop_duplicates()returns a new DataFrame, and.copy()makes sure later column assignments do not trigger aSettingWithCopyWarningor write through to another object.dfanddf_rawhave different names. Later cells usedf, anddf_rawstays available for comparison.- The
amountfilter states two rules: missing amounts are removed, and negative amounts are removed. Both come from the audit, and both should be explained in a markdown cell nearby. - The final print shows the cost of cleaning. If you expected to lose 2% of the rows and lost 40%, you want to know now.
Splitting rules into steps
One function works for a handful of rules. As the list grows, you want to see which rule removed which rows. Split each rule into its own function and run them in a list.
import numpy as np
import pandas as pd
def drop_duplicate_rows(df):
return df.drop_duplicates()
def normalize_region(df):
out = df.copy()
out["region"] = out["region"].str.strip().str.lower()
return out
def drop_invalid_amounts(df):
return df[df["amount"].notna() & (df["amount"] >= 0)]
def run_steps(df, steps):
for step in steps:
before = len(df)
df = step(df)
print(f"{step.__name__}: {before} -> {len(df)} rows")
return df
raw = pd.DataFrame({
"order_id": [1, 1, 2, 3, 4],
"region": ["North", "north ", "south", "East", "East"],
"amount": [10.0, 10.0, 20.0, -5.0, np.nan],
})
steps = [normalize_region, drop_duplicate_rows, drop_invalid_amounts]
clean = run_steps(raw, steps)
print(clean)The output is:
normalize_region: 5 -> 5 rows
drop_duplicate_rows: 5 -> 4 rows
drop_invalid_amounts: 4 -> 2 rows
order_id region amount
0 1 north 10.0
2 2 south 20.0The steps list is the plan for the whole cleaning stage. To disable a rule, you comment out one line. To add a rule, you write one function and insert it. The log tells you which rule removed the rows.
Step order changes the result
Order is part of the cleaning logic. In the example, orders 1 and 1 differ only by case and trailing space ("North" and "north "), so they are duplicates only after normalization. If you deduplicate first, the two rows survive.
wrong_order = [drop_duplicate_rows, normalize_region, drop_invalid_amounts]
print(len(run_steps(raw, wrong_order)))This prints three log lines (5 to 5, 5 to 5, 5 to 3) and then 3. The result keeps an order that appears twice. A comment next to the list helps the next reader:
# Normalize text before deduplicating, so "North" and "north " match.
steps = [normalize_region, drop_duplicate_rows, drop_invalid_amounts]Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `SettingWithCopyWarning` after filtering | Assigning to a column of a slice of another DataFrame | Call `.copy()` after the filter, or at the start of a step that assigns columns |
| `df_raw` changes after calling a step | A step modified its input in place (for example `df["x"] = ...` without a copy) | Copy first, return the new object |
| `AttributeError: Can only use .str accessor with string values` | The column is numeric or mixed after a bad load | Check dtypes in the quality report; convert in a separate step before string cleaning |
| Different row counts on each run | Cells were executed out of order, or a step was run twice | Run the steps from one list in one cell |
| Rows vanish unexpectedly | A comparison with `NaN` evaluates to `False`, so a filter silently drops missing values | Write the missing-value rule explicitly, as `notna()` above |
Checking that cleaning is re-runnable
"Re-runnable" has two meanings you can test:
- Idempotent: cleaning data that is already clean changes nothing.
- Deterministic: the same raw input always gives the same output.
Both checks fit in a few lines.
once = run_steps(raw, steps)
twice = run_steps(once, steps)
pd.testing.assert_frame_equal(once, twice)assert_frame_equal raises an AssertionError that describes the difference if the frames do not match. Here the second run removes zero rows at every step, so the assertion passes.
A second kind of check confirms that the output satisfies the rules, no matter how it was produced:
def check_clean(df):
assert not df.duplicated().any(), "duplicate rows remain"
assert df["amount"].notna().all(), "missing amounts remain"
assert (df["amount"] >= 0).all(), "negative amounts remain"
return df
check_clean(clean)Put check_clean at the end of the cleaning section. If someone edits a step later and breaks a rule, the notebook stops at that cell instead of producing a plot from bad data.
Deciding what to do with each problem
The audit finds problems, but it does not say what to do about them. For each finding, choose an action and record why.
- Exact duplicate rows: drop them if the audit shows they are copies of the same event. If two real orders can look identical, dropping them loses data, so check for a key such as
order_idfirst. - Inconsistent text: normalize it (strip, lowercase) and then check the distinct values again.
- Impossible values: a negative
amountmight be a refund or a data entry error. Dropping it is a decision about the business meaning. Consider keeping those rows in a separate DataFrame (df_rejected) so you can examine them later. - Missing values: dropping is only one option. You can also keep the rows and handle the gaps in each analysis, or fill values. Fill only when you can justify the value, and add an indicator column so the fill stays visible.
Document each decision
Add a markdown cell above the cleaning code that lists every rule, the audit evidence for it, and the number of rows it affects. For example:
### Cleaning decisions
- **Normalize region text** (strip, lowercase): the audit found `"North"`, `"north "`, and `"NORTH"` as separate values.
- **Drop duplicate rows:** the audit counted 12 fully duplicated rows.
- **Drop missing or negative amounts:** 31 rows. Negative values need confirmation with the data owner; they may be refunds.The numbers in this cell should match the log your code prints. If they drift apart after an edit, one of them is wrong.
Summary
- Write each cleaning rule as a function that takes a DataFrame and returns a new one.
- Never overwrite
df_raw, and use a different output name from the input. - Run the steps from a list, print row counts per step, and treat the order of the list as part of the logic.
- Test idempotence with
assert_frame_equal, and test the rules with acheck_cleanfunction. - Record each decision, with its evidence, in markdown beside the code.
Exercise
A colleague's notebook runs drop_duplicate_rows before normalize_region. The region column contains "West" and "west " for otherwise identical orders. What happens, how would the row-count log show it, and how do you fix it?
Show answer
The two rows are not exact duplicates before normalization, so drop_duplicate_rows keeps both. The log shows no rows removed (for example, 5 -> 5) at the dedupe step, and the duplicate survives into the analysis, where it inflates totals for the west region. Fix it by putting normalize_region first in the steps list, then re-running and confirming that the dedupe step now removes a row. Add a check_clean assertion on df.duplicated() so the problem fails loudly in the future.
Exercise
You run clean = run_steps(raw, steps) and then again = run_steps(clean, steps). What should the log for the second run show if the steps are idempotent, and what does it mean if a step still removes rows?
Show answer
Every step should print the same row count before and after (for example, 2 -> 2). If a step still removes rows on the second run, then the earlier steps leave behind data that this step rejects. This usually means the steps are in the wrong order, or one step creates the problem that another removes.