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.

5 min readUpdated 2026-11-30
In This Lesson
  • 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.

4-Stage Dirty Data Cleaning Funnel

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:

python
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' / str

Look 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 RoleExampleBest StrategyPandas Pattern
Critical ID or targetorder_id, amountDrop (and count/log!)df.dropna(subset=["order_id", "amount"])
Optional categorycountry, couponFill with explicit labeldf["country"].fillna("Unknown")
True zero countrefund_amount, itemsFill with 0df["refund_amount"].fillna(0.0)
Skewed continuous featureage, session_secFill with median() + flagdf["age"].fillna(df["age"].median())
Time-series gapDaily sensor / stock priceForward-fill (carefully)df["price"].ffill()
Don't Confuse Missing With Zero

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.

python
# 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

  1. .str.strip().str.lower(): Eliminates leading/trailing whitespace and casing mismatches before any groupby or merge runs.
  2. .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.
  3. .str.replace(r"[$,]", "", regex=True): Strips currency symbols and thousands commas ("$1,250.00" → "1250.00").
  4. .pipe(pd.to_numeric, errors="coerce"): Converts valid numeric strings to float64 and turns garbage like "N/A" or "TBD" into NaN instead of crashing the script.
  5. 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.
errors='coerce' Is Your Safety Net

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:

Python 3Try It Live: Cleaning Dirty Order Records
Output

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

Check Your Understanding

Why can running df.dropna() without arguments accidentally wipe out most of a valid dataset?

Check Your Understanding

What does pd.to_numeric(series, errors='coerce') do when it encounters 'N/A'?

Check Your Understanding

You have duplicate email entries like 'Maya@Mail.com ' and 'maya@mail.com'. What order should you run cleaning steps?