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.
- 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:
| Step | Operation | Why It Happens in This Order |
|---|---|---|
| 1. Filter status | Keep only status.strip().lower() == "paid" | Exclude cancelled/refunded rows before summing revenue |
| 2. Deduplicate ID | Track seen tx_id (stripped) and skip repeats | Prevent double-counting webhook retries |
| 3. Coerce amount | Strip $ and ,, parse float, skip invalid or <= 0 | Avoid 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 KPIs | Compute count, revenue, avg rounded to 2 decimals | Produce clean per-region business metrics |
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:
- Keep only rows where
status.strip().lower() == "paid". - Deduplicate by
tx_id(strip whitespace first, keep the first occurrence). - Parse
amount("$1,080.00"→1080.0); skip rows with unparseable or<= 0amounts. - Normalize
regionwith.strip().upper()(defaulting blank orNoneto"UNKNOWN"). - Return a dictionary
{region: {"count": int, "revenue": float, "avg": float}}withrevenueandavgrounded to 2 decimals. - Uncomment the
assertblock at the bottom and run to verify every edge case passes!
Click “Run Code” to execute this snippet right in your browser.
Walkthrough of Common Edge Cases
- Why strip
tx_idbefore checkingseen? 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 <= 0filtered out? Refund reversals or$0promo tests shouldn't inflate paid order counts or drag down average order value (avg). - How does
round(..., 2)protect against float drift? Adding floats like45.50 + 12.10in IEEE-754 binary math can produce57.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:
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 doneIn clean_and_summarize, why do we strip $ and , BEFORE calling float(raw_amt)?
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?