2. Tabular Data Mastery with Pandas
Cleaning Messy Datasets: Missing Values, Duplicates & Type Parsing
Spend less time fighting dirty CSVs: inspect NaNs with isna(), decide between dropna() vs fillna(), remove duplicates, normalize messy strings, and fix broken numeric/date types.
- Audit missing values and duplicates before computing any metrics
- Choose deliberately between dropping rows, imputing values (median/0), or flagging missingness
- Normalize messy currency strings, whitespace, casing, and malformed dates cleanly
Real-world datasets are never clean. Pull a monthly export from a CRM, Shopify store, or Google Form and you will immediately hit " Maya ", "$1,250.00", "N/A", blank cells (NaN), duplicate webhook retries, and dates formatted three different ways. Data cleaning is 70% of real analytics work—and doing it systematically prevents silent bugs in every downstream chart and KPI.
1. Raw CSV
"$1,200", "N/A", dupes
2. Normalize
.strip().lower() + $
3. Coerce & Dedupe
errors='coerce' + drop_duplicates
4. Audit & Clean
Track rejected % → Ready!
Normalize text before deduplicating, coerce bad numbers to NaN/None safely, and log rejected counts so silent upstream schema shifts are caught early.
1. The 4-Line Dirtiness Audit
Before altering a single row, run a fast diagnostic on any newly loaded DataFrame so you know what is broken:
print(df.isna().sum()) # Missing count per column
print(df.duplicated().sum()) # Exact full-row duplicates
print(df.duplicated(subset=["order_id"]).sum()) # Duplicate primary keys!
print(df.dtypes) # Spot numbers trapped as 'object' / strLook closely at df.dtypes: if amount or ordered_at shows up as object (or str) instead of float64 / datetime64, at least one dirty string like "TBD" or "$1,200" is blocking numeric/date math.
2. Handling Missing Values: dropna() vs fillna()
Never blindly run df.dropna() across an entire DataFrame! If an optional promo_code or delivery_notes column is 85% empty, df.dropna() silently deletes 85% of your valid orders!
Instead, decide column by column based on business meaning:
| Column Role | Example | Best Strategy | Pandas Pattern |
|---|---|---|---|
| Critical ID or target | order_id, amount | Drop (and count/log!) | df.dropna(subset=["order_id", "amount"]) |
| Optional category | country, coupon | Fill with explicit label | df["country"].fillna("Unknown") |
| True zero count | refund_amount, items | Fill with 0 | df["refund_amount"].fillna(0.0) |
| Skewed continuous feature | age, session_sec | Fill with median() + flag | df["age"].fillna(df["age"].median()) |
| Time-series gap | Daily sensor / stock price | Forward-fill (carefully) | df["price"].ffill() |
Filling a missing customer age or satisfaction_score with 0 drags down averages horribly! Only fill NaN with 0 when missing genuinely means zero quantity (like discount_applied = 0 or items_returned = 0).
3. Deduplicating, Normalizing Strings & Coercing Types
Order matters when cleaning! If " maya@mail.com " and "Maya@mail.com" are actually the same customer, normalize text first so deduplication catches both.
# 1. Normalize text columns cleanly with the .str accessor
df["email"] = df["email"].str.strip().str.lower()
df["category"] = df["category"].fillna("Uncategorized").str.strip().str.title()
# 2. Sort chronologically so keep="last" preserves the most recent update
df["updated_at"] = pd.to_datetime(df["updated_at"], errors="coerce")
df = (
df.sort_values("updated_at")
.drop_duplicates(subset=["order_id"], keep="last")
)
# 3. Strip "$" and "," then parse numbers safely (invalid -> NaN)
df["amount"] = (
df["amount"]
.astype(str)
.str.replace(r"[$,]", "", regex=True)
.pipe(pd.to_numeric, errors="coerce")
)
# 4. Track how many rows failed parsing BEFORE dropping them!
bad_amount_count = int(df["amount"].isna().sum())
df = df.dropna(subset=["amount"]).copy()Line-by-Line Walkthrough of the Cleaning Pipeline
.str.strip().str.lower(): Eliminates leading/trailing whitespace and casing mismatches before anygroupbyormergeruns..sort_values(...).drop_duplicates(subset=["order_id"], keep="last"): Guarantees deterministic deduplication—when a webhook retries an order update, you keep the newest state rather than whichever row happened to appear first..str.replace(r"[$,]", "", regex=True): Strips currency symbols and thousands commas ("$1,250.00"→"1250.00")..pipe(pd.to_numeric, errors="coerce"): Converts valid numeric strings tofloat64and turns garbage like"N/A"or"TBD"intoNaNinstead of crashing the script.- Tracking
bad_amount_count: Acts as an upstream quality monitor—if a vendor changes formatting tomorrow, your rejected count spikes immediately instead of silently shipping half-empty numbers.
Both pd.to_numeric(col, errors="coerce") and pd.to_datetime(col, errors="coerce") convert unparseable entries into NaN/NaT cleanly. Always pair errors="coerce" with a check like if bad_rate > 0.05: log_warning(...) so silent corruption never slips past unnoticed.
Try It Yourself in the Playground
Clean a realistic dirty CSV batch in pure Python—normalizing whitespace and casing, deduplicating by order_id (keeping the latest row), parsing "$1,200.00", coercing "N/A" safely, and counting rejected rows:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why is it important to log or count rejected_rows (rows coerced to NaN/None) instead of silently discarding them?
Quick Checkpoints
Why can running df.dropna() without arguments accidentally wipe out most of a valid dataset?
What does pd.to_numeric(series, errors='coerce') do when it encounters 'N/A'?
You have duplicate email entries like 'Maya@Mail.com ' and 'maya@mail.com'. What order should you run cleaning steps?