Skip to content

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:

Terminal
python clean_sales.py data/sales_raw.csv output/sales_clean.csv

The 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).

  • 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.csv and data/stores.csv: the reference tables for prices, product names and regions.
  • data/config.json holds the business rules: quantities from 1 to 50, discounts up to 0.2, the three missing tokens and the three date formats.

Your script must:

  1. Take the source and target paths as command-line arguments (argparse), with an optional --data-dir for the reference tables (default data).
  2. Read the raw file with keep_default_na=False and the three tokens.
  3. Implement each cleaning step as a function that takes a DataFrame and returns (new_df, changed). Steps must not change their input.
  4. 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, filling unit_price and region from the reference tables, repairing impossible quantities from revenue, recovering missing discounts from revenue and labeling missing channels unknown.
  5. Fail fast: a step raises a ValueError with 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.
  6. Keep customer_id gaps as gaps. Do not invent customers.
  7. Build the cleaning log in a loop over the list of steps, and print it as a table.
  8. 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).
  9. Write the clean file and cleaning_log.csv next to it only when validation passes. Exit with code 0 on success and 1 on failure.

The expected report:

Expected output
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 36
fill_from_reference 1164 1164 26
repair_quantity 1164 1164 10
fill_discount 1164 1164 23
label_channel 1164 1164 17
Gaps left: {'customer_id': 23}
Validation passed: 0 problems
Wrote 1164 rows to output/sales_clean.csv
  1. Start with the skeleton. Write main(argv) with argparse, read the three files and print their shapes. Run it.

  2. Write the first step. price_to_float(df) returns df.assign(unit_price=...) and the number of converted cells. Compare the gap count before and after, and raise a ValueError if it grew.

  3. Write the pipeline loop. run_pipeline(raw, steps) calls each step, records step.__name__, the row counts and changed, and returns the clean table and the log as a DataFrame. Run it with one step, then add the others one by one.

  4. Add the text and date steps. For the change count of region, remember that NaN != NaN is True. For the dates, use one to_datetime per format and combine_first. Raise if any NaT remains.

  5. 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).

  6. 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.

  7. Validate. Write validate() and test it on a broken copy before you trust it.

  8. Write the outputs. Create the target folder with mkdir(parents=True, exist_ok=True). Use index=False. Write the log next to the clean file.

  9. 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 (starter)
"""clean_sales.py: a repeatable cleaning pipeline for the point-of-sale export."""
import argparse
from 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())
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
  1. Read NA_TOKENS, DATE_FORMATS and the quantity limits from data/config.json instead of constants, so that a business change needs no code change.
  2. Add a --quarantine PATH option: 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.
  3. 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.
  4. Add a revenue_suspect flag: 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.)
  5. 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.

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
"""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 argparse
from collections.abc import Callable
from pathlib import Path
import numpy as np
import 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())
Output
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 36
fill_from_reference 1164 1164 26
repair_quantity 1164 1164 10
fill_discount 1164 1164 23
label_channel 1164 1164 17
Gaps left: {'customer_id': 23}
Validation passed: 0 problems
Wrote 1164 rows to output/sales_clean.csv

How it works:

  1. 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.
  2. Steps as functions. Each step returns a new table built with assign and 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.
  3. Fail fast. price_to_float raises when the gap count grows, parse_dates raises on any value that matches no format, and fill_from_reference raises when a known price or region contradicts the reference table. A new kind of dirt stops the run instead of slipping through.
  4. A closure for the reference tables. make_fill_from_reference returns a step that remembers products and stores. The pipeline loop then treats every step the same way: df, changed = step(df).
  5. 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.
  6. The log. run_pipeline builds it from step.__name__ and the counts. normalize_text changed 354 cells: 259 regions and 95 product names. fill_from_reference filled 26 cells: 9 prices and 17 regions.
  7. 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.