12 · Lab: clean a messy export and report its quality

Run it in Colab View the .ipynb

You are reading this notebook. To run it, open it in Colab with the button above - no install, no GPU needed for most of them - or clone the repository and open it in Jupyter.

  1. The plan
  2. Step 1 · Load the file
    1. Exercise 1 · load_raw(path)
  3. Step 2 · Duplicates
    1. Exercise 2 · remove_duplicates(df)
  4. Step 3 · Dates
    1. Exercise 3 · parse_dates(df)
  5. Step 4 · Text
    1. Exercise 4 · clean_text(df)
  6. Step 5 · Units
    1. Exercise 5 · fix_prices(df)
  7. Step 6 · Unknown and impossible values
    1. Exercise 6 · handle_impossible(df)
  8. Step 7 · The quality report
    1. Exercise 7 · quality_report(df)
  9. Use it: the answer finance asked for
  10. Quiz
  11. Reflection
  12. What to show in your portfolio
  13. Going further
  14. Record your progress

Week 3 · lab · about 90 minutes

The situation. The finance team sends you data/course/messy_orders.csv, an order export from an old shop system (a synthetic file, generated for this course), and asks for revenue per city. Before anyone computes a number from it, you will turn it into a clean table with a small pipeline of functions, and hand over a quality report that says what the cleaned data looks like. Next month the same export will arrive again with new rows, so your code must work on any file of this kind, not just this one.

What you will practise: everything from notebook 11 (missing-value codes, duplicates, mixed dates, text, units, impossible values, validation), combined into one pipeline. There are no new concepts.

What you need: notebooks 10 and 11.

How grading works: there are seven steps; each is a function. Each grader gives your function the correct output of the previous steps (so a mistake in step 2 does not fail step 5), and runs it on the course file and on a freshly generated file with a different random seed. Hard-coded row numbers or values will not pass.

# --- Setup: works in Google Colab AND on your own computer. Safe to re-run. ---
# In Colab this downloads the course (about 30 s) and installs what it needs (about a minute, once
# per session). On your computer it just finds the course folder.
import os, sys, subprocess
from pathlib import Path

if "google.colab" in sys.modules and not Path("/content/mlengineering").exists():
    subprocess.run(["git", "clone", "--depth", "1",
                    "https://github.com/berdakh/mlengineering.git", "/content/mlengineering"], check=True)
    subprocess.run([sys.executable, "-m", "pip", "install", "-q", "-r",
                    "/content/mlengineering/requirements.txt"], check=True)
REPO_ROOT = Path("/content/mlengineering") if "google.colab" in sys.modules else next(
    p for p in [Path.cwd(), *Path.cwd().parents] if (p / "src" / "mlcourse").is_dir())
os.chdir(REPO_ROOT)
sys.path.insert(0, str(REPO_ROOT / "src"))
from mlcourse.grader import grade, quiz
print("Ready. Course folder:", REPO_ROOT)

The plan

Step Function What it does
1 load_raw(path) read the file, turning missing-value codes into NaN
2 remove_duplicates(df) drop exact duplicate rows
3 parse_dates(df) turn order_date into real dates
4 clean_text(df) standardise city and status
5 fix_prices(df) convert every price to dollars
6 handle_impossible(df) deal with unknown and impossible values
7 quality_report(df) validation: a dict of checks on the clean table

Rules for every step: return a new DataFrame (never change the input), and do not hard-code anything that depends on this particular file (row numbers, counts, specific order ids).

The helper below runs the first n steps you have written, so you can look at the result of your pipeline so far after each exercise. You do not need to change it.

import pandas as pd

RAW = "data/course/messy_orders.csv"
STEP_NAMES = ["load_raw", "remove_duplicates", "parse_dates", "clean_text", "fix_prices", "handle_impossible"]


def run_steps(n, path=RAW):
    """Run the first n pipeline steps (defined further down in this notebook) on the file at `path`."""
    data = path
    for name in STEP_NAMES[:n]:
        data = globals()[name](data)
    return data

Step 1 · Load the file

Look at the raw file first. Find every way this export writes “unknown” in a text or number column (notebook 11, section 1 showed how to look).

peek = pd.read_csv(RAW, dtype=str, keep_default_na=False)   # everything as plain text, nothing treated as missing
for col in ["city", "discount", "quantity"]:
    print(col, sorted(peek[col].unique())[:12])

Exercise 1 · load_raw(path)

Read the CSV at path so that the codes "N/A", "n/a", "-" and an empty field become missing values (NaN) in every column. Keep all rows and columns as they are otherwise (-1 in quantity is handled in step 6, not here). discount should come out as numbers.

def load_raw(path):
    # YOUR CODE HERE
    raise NotImplementedError()


step1 = run_steps(1)
print(step1.shape)
step1.isna().sum()
grade("w03.lab_load", load_raw)

Step 2 · Duplicates

Exercise 2 · remove_duplicates(df)

Remove exact duplicate rows (identical in every column), keeping the first copy, and reset the index to 0, 1, 2, …. After this step, check whether any order_id is still repeated: if one were, it would be a conflict to investigate, not a copy.

def remove_duplicates(df):
    # YOUR CODE HERE
    raise NotImplementedError()


step2 = run_steps(2)
print(len(step2), "rows; repeated order_id:", step2["order_id"].duplicated().sum())
grade("w03.lab_dedupe", remove_duplicates)

Step 3 · Dates

Exercise 3 · parse_dates(df)

Return the table with order_date converted to a datetime column. The column mixes 2025-03-04, 04/03/2025 (day first) and March 4, 2025, sometimes with spaces around. Every value must be parsed, and parsed correctly (remember the trap from notebook 11). All other columns are unchanged.

def parse_dates(df):
    # YOUR CODE HERE
    raise NotImplementedError()


step3 = run_steps(3)
print("unparsed dates:", step3["order_date"].isna().sum())
print("from", step3["order_date"].min().date(), "to", step3["order_date"].max().date())
grade("w03.lab_dates", parse_dates)

Step 4 · Text

Exercise 4 · clean_text(df)

Standardise two text columns:

  • city: spaces removed at both ends, title case (" ALMATY" becomes "Almaty");
  • status: spaces removed at both ends, lower case (" DELIVERED" becomes "delivered").

Missing values stay missing. All other columns are unchanged.

def clean_text(df):
    # YOUR CODE HERE
    raise NotImplementedError()


step4 = run_steps(4)
print(step4["status"].value_counts(), "\n")
print(step4["city"].value_counts(dropna=False))
grade("w03.lab_text", clean_text)

Step 5 · Units

Exercise 5 · fix_prices(df)

Some prices are in cents (price_unit == "cents"). Convert those to dollars (divide by 100), round every price to 2 decimals, and drop the price_unit column. Leave zero and negative prices alone for now (step 6).

def fix_prices(df):
    # YOUR CODE HERE
    raise NotImplementedError()


step5 = run_steps(5)
step5.groupby("product")["unit_price"].agg(["min", "median", "max"])

Look at the table: each product should have one typical price. The minimum column shows the values step 6 has to deal with.

grade("w03.lab_prices", fix_prices)

Step 6 · Unknown and impossible values

This step contains decisions. Here are the ones the finance team agreed to; your function must implement exactly these, and the quality report will document their effect.

  1. quantity == -1 is the old system’s code for “unknown”: make it a missing value (NaN). The row stays.
  2. Any other negative quantity is impossible: drop the row.
  3. A unit_price of 0 or below is impossible: drop the row.
  4. A missing discount means no discount was recorded: fill it with 0.0.
  5. Reset the index to 0, 1, 2, ….

Exercise 6 · handle_impossible(df)

Watch out: comparisons with NaN are False, so df["quantity"] < 0 is False for an unknown quantity. That is what you want here (rule 1 keeps those rows), but think about the order of rules 1 and 2.

def handle_impossible(df):
    # YOUR CODE HERE
    raise NotImplementedError()


clean = run_steps(6)
print(len(clean), "rows")
clean.describe()
grade("w03.lab_impossible", handle_impossible)

Step 7 · The quality report

Cleaning is done; now validation. The report is a dict that a reviewer (or the next step of a pipeline) can read. Values must be plain Python int and bool (wrap pandas results in int(...) / bool(...)).

Exercise 7 · quality_report(df)

Given the cleaned table, return a dict with exactly these keys:

Key Value
"rows" number of rows
"duplicate_order_ids" how many rows repeat an order_id already seen (0 is the goal)
"missing_quantity" number of rows with unknown quantity
"missing_city" number of rows with missing city
"dates_in_range" True if every order_date is between 2024-01-01 and 2025-12-31 (inclusive)
"prices_positive" True if every unit_price is greater than 0
"statuses_valid" True if every status is one of delivered, shipped, cancelled, returned

The function only looks; it does not clean. The grader also breaks a price on purpose to check that your check notices.

def quality_report(df):
    # YOUR CODE HERE
    raise NotImplementedError()


report = quality_report(run_steps(6))
report
grade("w03.lab_report", quality_report)

Use it: the answer finance asked for

With a clean table, the original question takes three lines. Revenue counts delivered orders only; rows with an unknown quantity cannot contribute a revenue and are left out (and the report says how many there were).

clean = run_steps(6)
delivered = clean[(clean["status"] == "delivered") & clean["quantity"].notna()]
revenue = delivered["quantity"] * delivered["unit_price"] * (1 - delivered["discount"])
delivered.assign(revenue=revenue).groupby("city", dropna=False)["revenue"].sum().round(2).sort_values(ascending=False)

Try it. Compute the same revenue per city from the raw file, the naive way (pd.read_csv(RAW), group by city, sum quantity * unit_price). How different are the numbers, and how many “cities” are there? This is the answer you would have sent without cleaning.

# Try it.

Quiz

Q1. Why write each cleaning step as a separate function instead of fixing the CSV by hand in a spreadsheet?

  • a) Editing the CSV by hand is faster and just as reliable.
  • b) Functions can be tested, reviewed, reordered and rerun on next month’s file.
  • c) It is best to put every fix in one long cell.
  • d) So you can save the cleaned data over the raw file.
answer = "?"
quiz("w03.12_q1", answer)

Q2. Why does removing duplicates come before computing anything else?

  • a) Dates must be parsed before duplicates can be found.
  • b) The order of the steps does not matter.
  • c) Every count and total computed before deduplication is inflated by the copies.
  • d) Impossible values should always be dropped first.
answer = "?"
quiz("w03.12_q2", answer)

Q3. What is the quality report for?

  • a) It is evidence of what the cleaned data looks like, so a reviewer can trust it or question it, and a pipeline can stop when a check fails.
  • b) It fixes the remaining problems automatically.
  • c) It is only needed for very large datasets.
  • d) It replaces the cleaning steps.
answer = "?"
quiz("w03.12_q3", answer)

Q4. You filled missing discounts with 0.0. What else should you do?

  • a) Nothing: 0 is always the correct fill value.
  • b) Drop those rows instead, to be safe.
  • c) Use the mean discount, which is more accurate.
  • d) Write the assumption down (“no discount recorded = no discount”) so others can check or disagree with it.
answer = "?"
quiz("w03.12_q4", answer)

Reflection

Write three or four sentences in a text cell (or your own notes):

  • Which problem in this file would have hurt a model most if you had missed it, and why?
  • Which of the step-6 decisions would you question if you were on the finance team?
  • If next month’s file had a fourth date format, which part of your pipeline would catch it, and how? (Hint: what does step 3 produce for a value it cannot parse, and which check would notice?)

What to show in your portfolio

A short, honest data-cleaning write-up is a strong portfolio piece. Show: the list of problems you found (with counts), the pipeline as seven small functions, the quality report before and after, and the decisions you made about missing values with one sentence of justification each. Say clearly that the data is synthetic.

Going further

Record your progress

Flags: reading, guided (you passed the graded exercises), independent (you solved them without hints or solutions), review (come back to this).

from mlcourse.progress import mark

# mark("12", "reading")
# mark("12", "guided")

Back to top

Applied ML Engineering course materials. Code is MIT licensed; prose is CC BY 4.0. The SKAB dataset is GPL-3.0 and is downloaded from its source, not redistributed here.