26. Data cleaning — Mini-project
The shop’s old point-of-sale system sends a new export every week. The analytics team wants a clean table every Monday, and an auditor wants to know what was changed and why. Cleaning by hand in a notebook fails both needs: nobody can rerun it, and nobody can see what it did.
Write clean_sales.py, a command-line script that cleans the export in fixed, small steps, prints a cleaning report (one line per step with the rows in, the rows out and the cells or rows changed), validates the result and writes the clean file only when every rule passes:
python clean_sales.py data/sales_raw.csv output/sales_clean.csvThe project combines the whole module: missing-value tokens, type fixes, text normalization, safe date parsing, duplicates, repairs from trusted sources, labels for unknown values, validation and a cleaning log. It also reuses module 08 (argparse, main()) and module 05 (functions as values).
Dataset
Section titled “Dataset”data/sales_raw.csv: 1,200 lines, 13 columns. The data dictionary lists every injected problem. The counts you need:
| Problem | Count |
|---|---|
Missing tokens "", N/A, - (customer_id 23, region 17, channel 17, unit_price 10, discount 24) |
91 cells |
Prices as text with $ (47 also with a thousands separator) |
1,190 |
| Region in wrong case or with spaces | 259 |
| Product names with stray spaces | 95 |
Dates as DD/MM/YYYY and Month D, YYYY (the rest ISO) |
276 + 201 |
| Exact duplicate rows | 36 |
| Quantities outside 1–50 | 10 |
data/products.csvanddata/stores.csv: the reference tables for prices, product names and regions.data/config.jsonholds the business rules: quantities from 1 to 50, discounts up to 0.2, the three missing tokens and the three date formats.
Requirements
Section titled “Requirements”Your script must:
- Take the source and target paths as command-line arguments (
argparse), with an optional--data-dirfor the reference tables (defaultdata). - Read the raw file with
keep_default_na=Falseand the three tokens. - Implement each cleaning step as a function that takes a DataFrame and returns
(new_df, changed). Steps must not change their input. - Include at least these steps, in a sensible order: prices to float, text normalization (
region,product), date parsing with the three explicit formats, duplicate removal, fillingunit_priceandregionfrom the reference tables, repairing impossible quantities fromrevenue, recovering missing discounts fromrevenueand labeling missing channelsunknown. - Fail fast: a step raises a
ValueErrorwith a clear message when it meets something it cannot handle: a price that does not convert, a date in an unknown format, or a reference table that contradicts the data. - Keep
customer_idgaps as gaps. Do not invent customers. - Build the cleaning log in a loop over the list of steps, and print it as a table.
- Validate the clean table with a
validate(df, products, stores) -> list[str]function (required columns, key uniqueness, quantity range, allowed discounts and regions, the revenue formula, referential integrity). - Write the clean file and
cleaning_log.csvnext to it only when validation passes. Exit with code 0 on success and 1 on failure.
The expected report:
Cleaning report: data/sales_raw.csv step rows_in rows_out changed price_to_float 1200 1200 1190 normalize_text 1200 1200 354 parse_dates 1200 1200 477 drop_duplicates 1200 1164 36fill_from_reference 1164 1164 26 repair_quantity 1164 1164 10 fill_discount 1164 1164 23 label_channel 1164 1164 17Gaps left: {'customer_id': 23}Validation passed: 0 problemsWrote 1164 rows to output/sales_clean.csvStep plan
Section titled “Step plan”-
Start with the skeleton. Write
main(argv)withargparse, read the three files and print their shapes. Run it. -
Write the first step.
price_to_float(df)returnsdf.assign(unit_price=...)and the number of converted cells. Compare the gap count before and after, and raise aValueErrorif it grew. -
Write the pipeline loop.
run_pipeline(raw, steps)calls each step, recordsstep.__name__, the row counts andchanged, and returns the clean table and the log as a DataFrame. Run it with one step, then add the others one by one. -
Add the text and date steps. For the change count of
region, remember thatNaN != NaNisTrue. For the dates, use oneto_datetimeper format andcombine_first. Raise if anyNaTremains. -
Remove duplicates, then repair and fill. Order matters. Repairing a quantity needs the price and the discount; recovering a discount needs the price and a correct quantity. Check that every repaired value is plausible (whole quantities from 1 to 50, discounts in the allowed list).
-
Use a closure for the reference step. The reference tables are not part of the DataFrame. A function factory
make_fill_from_reference(products, stores)(module 05) returns a step function that remembers them. -
Validate. Write
validate()and test it on a broken copy before you trust it. -
Write the outputs. Create the target folder with
mkdir(parents=True, exist_ok=True). Useindex=False. Write the log next to the clean file. -
Compare with the expected report. Every number must match, and every number must be explainable from the data dictionary.
A skeleton to start from:
"""clean_sales.py: a repeatable cleaning pipeline for the point-of-sale export."""
import argparsefrom pathlib import Path
import pandas as pd
NA_TOKENS = ["", "N/A", "-"]DATE_FORMATS = ["%Y-%m-%d", "%d/%m/%Y", "%B %d, %Y"]
def price_to_float(df: pd.DataFrame) -> tuple[pd.DataFrame, int]: # TODO: strip "$" and ",", convert, raise if new gaps appear ...
# TODO: the other steps, validate(), run_pipeline()
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Clean the point-of-sale export.") # TODO: source, target, --data-dir # TODO: read, run the steps, print the report, validate, write return 0
if __name__ == "__main__": raise SystemExit(main())Rubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Runs as a command | 2 | python clean_sales.py SOURCE TARGET works; --help describes the arguments |
| Explicit tokens | 1 | keep_default_na=False with the three tokens |
| Steps as functions | 3 | Every step is a function returning (df, changed) and does not change its input |
| Correct cleaning | 4 | The report matches the expected numbers exactly |
| Safe dates | 2 | Explicit formats with combine_first; no format="mixed" |
| Fail fast | 2 | Unknown prices, dates and reference conflicts raise a ValueError with a message |
| Validation | 3 | validate() covers ranges, allowed values, key, revenue rule and referential integrity |
| Outputs | 2 | Clean file and log written only on success; exit codes 0 and 1 |
| Readability | 1 | Constants at the top, docstrings, type hints |
| Total | 20 | 16 or more: you are ready for module 27 |
Stretch goals
Section titled “Stretch goals”- Read
NA_TOKENS,DATE_FORMATSand the quantity limits fromdata/config.jsoninstead of constants, so that a business change needs no code change. - Add a
--quarantine PATHoption: instead of failing on rows that break a rule, move them to a separate file and clean the rest. Report how many rows went there. - Write pytest tests (module 14) for three steps, each on a tiny hand-made DataFrame, plus one test that a broken date raises a
ValueError. - Add a
revenue_suspectflag: the z-score of log revenue per unit within each product. How many lines does it flag on this file, and why? (Hint: the unit price of a product never changes, so only the discount moves revenue per unit.) - Run the script twice and compare the two outputs byte by byte. A pipeline that gives the same result on the same input is deterministic; prove that yours is.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your names can differ; your report must not.
Reference solution
"""clean_sales.py: a repeatable cleaning pipeline for the point-of-sale export.
Usage: python clean_sales.py data/sales_raw.csv output/sales_clean.csv"""
import argparsefrom collections.abc import Callablefrom pathlib import Path
import numpy as npimport pandas as pd
NA_TOKENS = ["", "N/A", "-"]DATE_FORMATS = ["%Y-%m-%d", "%d/%m/%Y", "%B %d, %Y"]REGIONS = ["North", "South", "East", "West"]DISCOUNTS = [0.0, 0.05, 0.1, 0.2]KEY = ["order_id", "product_id"]MIN_QTY, MAX_QTY = 1, 50
Step = Callable[[pd.DataFrame], tuple[pd.DataFrame, int]]
# --- Steps: each returns the new table and the number of rows or cells changed ---def price_to_float(df: pd.DataFrame) -> tuple[pd.DataFrame, int]: text = df["unit_price"] price = pd.to_numeric(text.str.replace(r"[$,]", "", regex=True), errors="coerce") if price.isna().sum() != text.isna().sum(): raise ValueError("unit_price: some prices could not be converted") return df.assign(unit_price=price), int(text.notna().sum())
def normalize_text(df: pd.DataFrame) -> tuple[pd.DataFrame, int]: region = df["region"].str.strip().str.title() product = df["product"].str.strip().str.replace(r"\s+", " ", regex=True) changed = ((region != df["region"]) & df["region"].notna()).sum() changed += (product != df["product"]).sum() return df.assign(region=region, product=product), int(changed)
def parse_dates(df: pd.DataFrame) -> tuple[pd.DataFrame, int]: text = df["order_date"] parts = [pd.to_datetime(text, format=f, errors="coerce") for f in DATE_FORMATS] dates = parts[0] for part in parts[1:]: dates = dates.combine_first(part) if dates.isna().any(): bad = text[dates.isna()].tolist()[:5] raise ValueError(f"order_date: unknown format, for example {bad}") changed = (text != dates.dt.strftime("%Y-%m-%d")).sum() return df.assign(order_date=dates), int(changed)
def drop_duplicates(df: pd.DataFrame) -> tuple[pd.DataFrame, int]: out = df.drop_duplicates() return out, len(df) - len(out)
def repair_quantity(df: pd.DataFrame) -> tuple[pd.DataFrame, int]: implied = df["revenue"] / (df["unit_price"] * (1 - df["discount"])) whole = implied.round() bad = ~df["quantity"].between(MIN_QTY, MAX_QTY) fix = bad & ((implied - whole).abs() < 0.01) & whole.between(MIN_QTY, MAX_QTY) quantity = df["quantity"].mask(fix, whole).astype("int64") return df.assign(quantity=quantity, quantity_repaired=fix), int(fix.sum())
def make_fill_from_reference(products: pd.DataFrame, stores: pd.DataFrame) -> Step: price_ref = products.set_index("product_id")["unit_price"] region_ref = stores.set_index("store_id")["region"]
def fill_from_reference(df: pd.DataFrame) -> tuple[pd.DataFrame, int]: price = df["product_id"].map(price_ref) region = df["store_id"].map(region_ref) known_price = df["unit_price"].notna() known_region = df["region"].notna() if (df["unit_price"][known_price] != price[known_price]).any(): raise ValueError("unit_price conflicts with products.csv") if (df["region"][known_region] != region[known_region]).any(): raise ValueError("region conflicts with stores.csv") changed = (~known_price).sum() + (~known_region).sum() out = df.assign( unit_price=df["unit_price"].fillna(price), region=df["region"].fillna(region), ) return out, int(changed)
return fill_from_reference
def fill_discount(df: pd.DataFrame) -> tuple[pd.DataFrame, int]: implied = (1 - df["revenue"] / (df["unit_price"] * df["quantity"])).round(2) gap = df["discount"].isna() return df.assign(discount=df["discount"].fillna(implied)), int(gap.sum())
def label_channel(df: pd.DataFrame) -> tuple[pd.DataFrame, int]: gap = df["channel"].isna() return df.assign(channel=df["channel"].fillna("unknown")), int(gap.sum())
# --- Validation ---------------------------------------------------------------def validate( df: pd.DataFrame, products: pd.DataFrame, stores: pd.DataFrame) -> list[str]: """Return one message per failed rule. An empty list means the table is valid.""" problems = [] for c in ["order_id", "order_date", "store_id", "product_id", "unit_price"]: if df[c].isna().any(): problems.append(f"{c}: {df[c].isna().sum()} missing") if df.duplicated(subset=KEY).any(): problems.append(f"key: {df.duplicated(subset=KEY).sum()} duplicates") bad_qty = ~df["quantity"].between(MIN_QTY, MAX_QTY) if bad_qty.any(): problems.append(f"quantity: {bad_qty.sum()} outside {MIN_QTY}..{MAX_QTY}") if not df["discount"].isin(DISCOUNTS).all(): problems.append("discount: values outside the allowed list") if not df["region"].isin(REGIONS).all(): problems.append("region: unknown values") expected = df["unit_price"] * df["quantity"] * (1 - df["discount"]) if not np.isclose(expected, df["revenue"], atol=0.01).all(): problems.append("revenue: does not match price x quantity x (1 - discount)") for c, ref in [("store_id", stores), ("product_id", products)]: orphans = ~df[c].isin(ref[c]) if orphans.any(): problems.append(f"{c}: {orphans.sum()} orphan rows") return problems
# --- Pipeline -------------------------------------------------------------------def run_pipeline( raw: pd.DataFrame, steps: list[Step]) -> tuple[pd.DataFrame, pd.DataFrame]: """Run each step in order and return the clean table and the cleaning log.""" df, log = raw, [] for step in steps: rows_in = len(df) df, changed = step(df) log.append( { "step": step.__name__, "rows_in": rows_in, "rows_out": len(df), "changed": changed, } ) return df, pd.DataFrame(log)
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Clean the point-of-sale export.") parser.add_argument("source", type=Path, help="raw CSV, e.g. data/sales_raw.csv") parser.add_argument("target", type=Path, help="clean CSV to write") parser.add_argument("--data-dir", type=Path, default=Path("data")) args = parser.parse_args(argv)
raw = pd.read_csv(args.source, keep_default_na=False, na_values=NA_TOKENS) products = pd.read_csv(args.data_dir / "products.csv") stores = pd.read_csv(args.data_dir / "stores.csv") steps = [ price_to_float, normalize_text, parse_dates, drop_duplicates, make_fill_from_reference(products, stores), repair_quantity, fill_discount, label_channel, ] clean, log = run_pipeline(raw, steps)
print(f"Cleaning report: {args.source}") print(log.to_string(index=False)) gaps = clean.isna().sum() print("Gaps left:", gaps[gaps > 0].to_dict()) problems = validate(clean, products, stores) if problems: print("Validation FAILED:") for message in problems: print(" -", message) return 1 print("Validation passed: 0 problems") args.target.parent.mkdir(parents=True, exist_ok=True) clean.to_csv(args.target, index=False) log.to_csv(args.target.with_name("cleaning_log.csv"), index=False) print(f"Wrote {len(clean)} rows to {args.target}") return 0
if __name__ == "__main__": raise SystemExit(main())Cleaning report: data/sales_raw.csv step rows_in rows_out changed price_to_float 1200 1200 1190 normalize_text 1200 1200 354 parse_dates 1200 1200 477 drop_duplicates 1200 1164 36fill_from_reference 1164 1164 26 repair_quantity 1164 1164 10 fill_discount 1164 1164 23 label_channel 1164 1164 17Gaps left: {'customer_id': 23}Validation passed: 0 problemsWrote 1164 rows to output/sales_clean.csvHow it works:
- Constants first. The tokens, formats, allowed values and limits sit at the top. The validation and the steps read them, so a rule lives in one place.
- Steps as functions. Each step returns a new table built with
assignand a change count. None of them modifies its input, so the pipeline can compare before and after and a failed step leaves no half-changed data. - Fail fast.
price_to_floatraises when the gap count grows,parse_datesraises on any value that matches no format, andfill_from_referenceraises when a known price or region contradicts the reference table. A new kind of dirt stops the run instead of slipping through. - A closure for the reference tables.
make_fill_from_referencereturns a step that remembersproductsandstores. The pipeline loop then treats every step the same way:df, changed = step(df). - Order. Prices and regions come from the reference tables first. The quantity repair needs the price and the discount, and the 10 bad-quantity lines all have both. The discount recovery runs after the repair, because it divides by the quantity.
- The log.
run_pipelinebuilds it fromstep.__name__and the counts.normalize_textchanged 354 cells: 259 regions and 95 product names.fill_from_referencefilled 26 cells: 9 prices and 17 regions. - Validation and exit code. The script writes the files only when
validate()returns an empty list.raise SystemExit(main())turns the return value into the exit code, so a scheduler or a CI job sees the failure.
Alternative: pandas has DataFrame.pipe, which lets you write raw.pipe(step_a).pipe(step_b). It reads well for steps that return only a DataFrame. Here each step also returns a count, so an explicit loop over a list of steps is simpler and gives the log for free.