Part 06 / Stage 2
Messy data
Goal: Turn a real customer export — duplicates, mixed units, ambiguous dates, impossible values — into clean, validated records plus a quarantine report the customer can act on. Time: ~3.5 hours · Needs: Python 3.14+, the course venv (pandas and Pydantic are installed)
Customer data is never clean. Acme's export (tools/fdelab.py, SHIPMENTS_CSV) is eight rows long and contains an exact duplicate, weights in kg and lbs (one missing, one negative), three date formats, and four spellings of "delivered" — one of each problem you will meet at every customer, in a file small enough to check by eye.
What you will learn
- Profiling a dataset: counts, types, nulls, distinct values
- Normalising values: case, whitespace, units, enumerations
- Dates and time zones: ambiguous formats, and confirming them with the customer
- Duplicates, exact and near
- Validation with Pydantic: schemas as contracts
- Quarantine and reporting: keeping bad rows out, and telling the customer why
- Other enterprise formats: XML, fixed-width, Excel, SFTP drops
Topics in this part
Practice
Work in the course venv. The raw export is fdelab.SHIPMENTS_CSV; check each answer by running it, and compare with solutions/ only after trying.
Exercise 1: Profile the export
Print a profile of the raw export: row count, nulls per column (count empty strings too), distinct raw status values with counts, and the number of duplicated shipment_ids. No cleaning — the point is to see the mess measured.
Show the solution to Exercise 1
# Exercise 1: measure the mess before touching it
import csv, io
from collections import Counter
from fdelab import SHIPMENTS_CSV
rows = list(csv.DictReader(io.StringIO(SHIPMENTS_CSV)))
print("rows:", len(rows))
for col in rows[0]:
empty = sum(1 for r in rows if not r[col].strip())
print(f"empty {col}: {empty}")
print("status values:", dict(Counter(r["status"] for r in rows)))
ids = [r["shipment_id"] for r in rows]
print("duplicated ids:", len(ids) - len(set(ids)))
Exercise 2: Normalise one column
Write normalise_status(raw) and apply it to every row, printing raw -> clean once per distinct raw value. The clean set must be exactly {delivered, in_transit, delayed}.
Show the solution to Exercise 2
# Exercise 2: one normal form for status
import csv, io
from fdelab import SHIPMENTS_CSV
def normalise_status(raw):
return raw.strip().lower().replace(" ", "_")
seen = {}
for row in csv.DictReader(io.StringIO(SHIPMENTS_CSV)):
raw = row["status"]
if raw not in seen:
seen[raw] = normalise_status(raw)
print(f"{raw!r} -> {seen[raw]!r}")
assert set(seen.values()) == {"delivered", "in_transit", "delayed"}
print("clean set ok")
Exercise 3: A stricter schema
Extend the lesson's Pydantic Shipment with origin and destination (non-empty, stripped strings) and a rule that origin != destination. Feed it one good record and one with origin == destination, and print the validation error message for the bad one.
Show the solution to Exercise 3
# Exercise 3: routes must go somewhere
from datetime import date
from typing import Literal
from pydantic import BaseModel, Field, ValidationError, field_validator, model_validator
class Shipment(BaseModel):
shipment_id: str = Field(pattern=r"^S-\d{4}$")
customer: str
origin: str = Field(min_length=1)
destination: str = Field(min_length=1)
weight_kg: float = Field(gt=0)
status: Literal["delivered", "in_transit", "delayed"]
shipped_on: date
@field_validator("customer", "origin", "destination")
@classmethod
def strip(cls, v):
return v.strip()
@model_validator(mode="after")
def route_goes_somewhere(self):
if self.origin == self.destination:
raise ValueError("origin and destination must differ")
return self
good = Shipment(shipment_id="S-1001", customer="Bolt Retail", origin="Mumbai",
destination="Pune", weight_kg=120, status="delivered", shipped_on="2025-03-01")
print("good record ok:", good.shipment_id)
try:
Shipment(shipment_id="S-1009", customer="Kite Foods", origin="Chennai",
destination="Chennai", weight_kg=10, status="delayed", shipped_on="2025-03-09")
except ValidationError as e:
print("rejected:", e.errors()[0]["msg"])
Exercise 4: Near-duplicate detection
Two rows are near-duplicates when they share customer, origin, destination and date after normalisation. Find the near-duplicate pair in the export that is not an exact duplicate (hint: strip the customer field). Print the pair of ids.
Show the solution to Exercise 4
# Exercise 4: the near-duplicate hiding behind whitespace
import csv, io
from collections import defaultdict
from fdelab import SHIPMENTS_CSV
groups = defaultdict(list)
for row in csv.DictReader(io.StringIO(SHIPMENTS_CSV)):
key = (row["customer"].strip(), row["origin"].strip(), row["destination"].strip(),
row["shipped_on"].strip())
groups[key].append(row["shipment_id"])
for key, ids in groups.items():
if len(ids) > 1 and len(set(ids)) > 1: # same route+date, different ids
print("near-duplicates:", ids, "on", key)
elif len(ids) > 1:
print("exact duplicate:", sorted(set(ids)), "on", key)
Mini-project: The Acme cleaning job
One script: read SHIPMENTS_CSV, clean and normalise, validate with Pydantic, and print (1) the clean records and (2) a quarantine report with one actionable line per failure — the deliverable you would send to Meena at Acme.
A solution is in solutions/mini_acme_cleaning_job.py.
Stretch: add near-duplicate detection (same customer, route and date) and a one-screen data-profiling summary at the top of the report.
Common mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
| Cleaning before profiling | You fix the problems you imagined, not the ones present | Profile first; let counts drive the rules |
| Parsing ambiguous dates by guess | Wrong dates are invisible until they collide with reality | Confirm the convention; record it; encode it |
| Ignoring units | 300 lbs ≠ 300 kg, by a factor that ruins reports | Extract value + unit; convert explicitly; quarantine unknowns |
| Dropping bad rows silently | The customer finds the gap before you do | Quarantine with reasons; report it |
| "Fixing" invalid values | Fabricated data in a customer system | Quarantine; let the source fix it |
| Trusting XML from outside | Entity-expansion attacks | defusedxml for untrusted feeds |
Quick recap
- Profile the data first — nulls, distinct values, duplicates — because the profile writes your cleaning rules.
- Normalise case, whitespace, units, enumerations; convert units explicitly.
- Ambiguous dates are a customer conversation first and a coded rule second.
- Pydantic schemas are contracts: good rows pass, bad rows carry precise errors.
- Quarantine failing rows with their reasons; never drop or "fix" them silently.
- XML, fixed-width files, Excel and SFTP drops all need the same discipline, just in older wrappers.
Checklist
- I profiled the export before touching it.
- I cleaned 8 raw rows into 7 with normalised status, units and dates.
- I validated with Pydantic and quarantined 3 rows with reasons.
- I can explain why S-1002 stays quarantined until Acme answers.
- I parsed an XML feed and a fixed-width file with explicit layouts.
Read more: pandas user guide · Pydantic models · defusedxml