Sub topic 7
Cleaning with named, re-runnable steps
This chapter assumes you can write Python functions, use pandas DataFrames, and run cells in Jupyter. It also assumes you have loaded df_raw and looked at a quality report, as in the earlier chapters.
Why cleaning belongs in a function
Many notebooks clean data with scattered cells that change a DataFrame in place. Run one of those cells twice and the result can differ. Run them out of order and you get a different table than your colleague does. Nobody can say which rules were applied.
A better habit is to put every cleaning rule in one named function. The function takes a DataFrame and returns a new one. It never touches df_raw. You can call it again at any time and get the same result.
A first cleaning function
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)}")Each line is one decision:
drop_duplicates()removes rows that repeat in every column..copy()makes a separate table, so later edits do not touch the input or trigger pandas warnings about modifying a slice.str.strip().str.lower()makes" North"and"north"the same region.- The last filter drops rows with a missing or negative amount.
The final print shows how many rows survived. Always look at this number. A rule that quietly removes 30% of your data is a finding, not a detail.
Making each step visible
One function is fine for three rules. With more rules, split it into small steps and chain them. Each step gets a name that says what it does.
def drop_invalid_amounts(df):
return df[df["amount"].notna() & (df["amount"] >= 0)]
def normalize_region(df):
out = df.copy()
out["region"] = out["region"].str.strip().str.lower()
return out
def clean_orders_v2(df):
steps = [
lambda d: d.drop_duplicates(),
normalize_region,
drop_invalid_amounts,
]
out = df
for step in steps:
before = len(out)
out = step(out)
print(f"{len(out):>6} rows after step ({before - len(out)} removed)")
return out.copy()Now the log shows which step removed how many rows. If a number looks wrong, you know where to look.
Common errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Editing `df_raw` in place | You lose the original and cannot re-run | Return a new DataFrame from every function |
| Cleaning in several separate cells | Order and repeat runs change the result | Put all rules in one function or one step list |
| Dropping rows without counting | Large losses go unnoticed | Print row counts per step |
| Dropping every odd value | You may delete real extreme orders | Decide per rule, and note it in markdown |
Test that it is re-runnable
Run the function twice and compare the results. If cleaning is idempotent (applying it again changes nothing), the two tables match.
once = clean_orders(df_raw)
twice = clean_orders(once)
print(once.equals(twice))If this prints False, some rule depends on state it should not depend on. Fix that before you continue.
Exercise
Why does cleanorders call .copy() and return a new DataFrame instead of modifying dfraw directly?
Show answer
A new DataFrame keeps df_raw untouched, so you can re-run cleaning from the original at any time and get the same result. The copy also avoids pandas warnings about modifying a slice of another table.
Exercise
You add a rule that removes orders with amount above 10,000. The row count drops from 9,800 to 9,100. What should you do before moving on?
Show answer
Treat the 700 removed rows as a possible finding. Inspect them, decide whether they are errors or real large orders, and record the decision and reason in a markdown cell. If they are real, keep them or handle them separately.