2. Tabular Data Mastery with Pandas

Practice Lab 1: Clean & Aggregate Messy Sales Records

Apply Modules 1 and 2 in a live data-cleaning lab: deduplicate transactions, coerce dirty prices, filter outliers, and compute per-region KPIs verified by automated assertions.

5 min readUpdated 2026-11-30
In This Lesson
  • Normalize dirty text fields, currency strings, and duplicate transaction IDs
  • Aggregate revenue, order count, and average order value per region
  • Verify every cleaning rule against automated assert checks

Time to put Modules 1 and 2 into practice! Imagine your Finance team drops a raw regional sales CSV export onto your desk right before Monday's pipeline sync. Inside, you find trailing spaces (" north "), mixed casing ("PAID" vs "paid"), duplicate webhook rows (T1 appearing twice), "$1,080.00" formatted currency strings, "CANCELLED" orders that shouldn't count as revenue, and an "N/A" price cell.

Your job is to turn that raw dump into a clean, trustworthy regional KPI dictionary verified by automated assertions.

1. Step-by-Step Pipeline Architecture

Before writing code, trace the exact order of operations so steps never fight each other:

StepOperationWhy It Happens in This Order
1. Filter statusKeep only status.strip().lower() == "paid"Exclude cancelled/refunded rows before summing revenue
2. Deduplicate IDTrack seen tx_id (stripped) and skip repeatsPrevent double-counting webhook retries
3. Coerce amountStrip $ and ,, parse float, skip invalid or <= 0Avoid ValueError crashes on "N/A" or $0 test pings
4. Normalize region.strip().upper(), fallback to "UNKNOWN"Merge " north " and "north" into one "NORTH" bucket
5. Aggregate KPIsCompute count, revenue, avg rounded to 2 decimalsProduce clean per-region business metrics
Watch Out for Blank Region Strings & None

In Python, calling None.strip() raises AttributeError! Always guard potentially missing fields using (row.get("region") or "").strip().upper() or "UNKNOWN" so both None and "" normalize cleanly.

2. Your Mission

Implement clean_and_summarize(raw_rows) in the playground below:

  1. Keep only rows where status.strip().lower() == "paid".
  2. Deduplicate by tx_id (strip whitespace first, keep the first occurrence).
  3. Parse amount ("$1,080.00" → 1080.0); skip rows with unparseable or <= 0 amounts.
  4. Normalize region with .strip().upper() (defaulting blank or None to "UNKNOWN").
  5. Return a dictionary {region: {"count": int, "revenue": float, "avg": float}} with revenue and avg rounded to 2 decimals.
  6. Uncomment the assert block at the bottom and run to verify every edge case passes!
Python 3Lab 1: Clean & Aggregate Dirty Sales Data
Output

Click “Run Code” to execute this snippet right in your browser.

Walkthrough of Common Edge Cases

  • Why strip tx_id before checking seen? If row 1 has "T1" and row 3 has " T1 ", failing to .strip() treats them as distinct IDs and double-counts $120.00.
  • Why keep amount <= 0 filtered out? Refund reversals or $0 promo tests shouldn't inflate paid order counts or drag down average order value (avg).
  • How does round(..., 2) protect against float drift? Adding floats like 45.50 + 12.10 in IEEE-754 binary math can produce 57.599999999999994; rounding final aggregated outputs keeps JSON/CSV reports clean.
  • How would this look in Pandas? Once you run this logic locally on 500,000 rows, those same 5 steps map directly to vectorized Pandas calls:
python
clean = (
    df.loc[df["status"].str.strip().str.lower() == "paid"]
      .drop_duplicates(subset=["tx_id"], keep="first")
      .assign(
          region=lambda d: d["region"].fillna("").str.strip().str.upper().replace("", "UNKNOWN"),
          amount=lambda d: pd.to_numeric(d["amount"].str.replace(r"[$,]", "", regex=True), errors="coerce"),
      )
      .dropna(subset=["amount"])
      .loc[lambda d: d["amount"] > 0]
      .groupby("region", as_index=False)
      .agg(count=("tx_id", "count"), revenue=("amount", "sum"), avg=("amount", "mean"))
)

Lab Checklist & Quick Checkpoints

Lab 1 Completion Checklist

0/4 done
Check Your Understanding

In clean_and_summarize, why do we strip $ and , BEFORE calling float(raw_amt)?

Check Your Understanding

Suppose an order has tx_id='T1' with status='cancelled' first, and later tx_id='T1' with status='paid'. With our step order (filter paid BEFORE deduplicating), what happens?