Duplicate Removal & Outlier Detection
Deduplicate records and spot outliers with IQR, z-scores, and domain-aware checks.
In plain words
Remove rows that are exact repeats, and look carefully at unusually big or small values before deciding if they are errors.
Think of it like…
Proofreading a ledger: the same transaction written twice must be struck out once, but a very large payment isn't automatically a mistake: you check the invoice before crossing it out.
Where you’ve seen it
An e-commerce export has 1.04 million order rows, but a retry bug wrote some orders twice. df.duplicated(subset=["order_id"]).sum() finds 38,000 repeats; keeping the row with the latest updated_at fixes the revenue total by ₹2.1 crore. In the same data, 0.3 percent of orders exceed the IQR upper fence, and a check against B2B account flags shows they are legitimate bulk orders, so they stay, with a is_bulk feature added.
Words you’ll hear
- Subset key
- The columns that define sameness (order_id), as opposed to the full row.
- IQR rule
- Flag values outside [Q1 − 1.5·IQR, Q3 + 1.5·IQR], where IQR = Q3 − Q1.
- Z-score
- (x − mean) / std; values beyond about ±3 are candidates.
- Winsorising / capping
- Limiting extreme values to a percentile instead of deleting them.
Visual diagram
Theory & deep dive
Finding and removing duplicates
First decide what "duplicate" means. Exact full-row duplicates are easy (df.duplicated().sum()), but real data usually repeats a business key with slightly different details (a retried order with a new timestamp). Use subset= with the key, and choose which row survives deliberately: sort by a timestamp or completeness first, then drop_duplicates(subset=["order_id"], keep="last"). Inspect examples with df[df.duplicated(subset=["order_id"], keep=False)].sort_values("order_id") before deleting anything.
Near-duplicates ("Acme Pvt Ltd" vs "ACME Private Limited") need normalisation first: lowercase, strip punctuation, standardise suffixes, then match on the cleaned key, or use fuzzy matching (rapidfuzz) for review lists. Always compare row counts and key totals before and after, and keep the removed rows in a separate file so the decision can be audited.
df = df.sort_values("updated_at").drop_duplicates(subset=["order_id"], keep="last"), then assert df["order_id"].is_unique documents and enforces the result.
Detecting and handling outliers
The IQR rule is robust to skew: compute q1, q3 = s.quantile([0.25, 0.75]), iqr = q3 - q1, and flag values outside q1 - 1.5*iqr and q3 + 1.5*iqr. The z-score assumes a roughly normal distribution and is itself distorted by the outliers it hunts (a robust variant uses the median and MAD). Always look at a histogram or box plot, and examine outliers in context: a ₹98,000 order is odd for a grocery shopper and normal for a B2B account, so group-wise rules (per segment or per product) often work better than global ones.
Choose a treatment per cause. Data-entry or unit errors: fix or set to missing. Genuine extremes: keep, perhaps transform (log) or use robust models. Heavy tails that distort linear models: cap at the 1st and 99th percentiles (s.clip(lower, upper)). Rare events that matter (fraud, failures): keep and treat as the target of interest. Record each rule, the number of rows affected and the reason, since removal choices change every downstream number.
q1, q3 = df["amount"].quantile([.25, .75]); iqr = q3 - q1; mask = ~df["amount"].between(q1 - 1.5*iqr, q3 + 1.5*iqr) flags 0.3% of rows; check them against account_type and keep those that are B2B bulk orders.
How it works, step by step
Step 1 of 41. Define sameness
Choose the columns that identify a real-world record and check how many repeats exist.
- Example
- 38,000 repeats
When to use it & trade-offs
What it is
Duplicates are repeated records for the same real-world thing, found with df.duplicated(subset=[...]) and removed with drop_duplicates(subset=[...], keep="first"). Outliers are values far from the rest. Common detection rules are the IQR rule (below Q1 − 1.5·IQR or above Q3 + 1.5·IQR) and the z-score (more than about 3 standard deviations from the mean), but a statistical flag only marks a candidate: domain checks decide whether it's an error, a rare-but-real event or the most important row in the data.
Why it matters: Duplicates inflate counts and revenue, bias models and break joins; careless outlier removal throws away real signal such as fraud, VIP customers or equipment failures. Most disasters come from automatic rules applied without asking what the rows mean. This topic tests judgement as much as pandas syntax.
When to reach for it
- Deduplicating on business keys before aggregating
- Group-wise outlier checks per segment
- Capping heavy tails before linear models
When to avoid or be careful
- Dropping every point beyond 3σ automatically
- Calling
drop_duplicates()without a subset on messy data - Removing rows without logging the rule and count
Outlier rules and treatments
Strengths: Robust to the outliers themselves; simple.
Watch out: May flag many points in heavy-tailed data.
Strengths: Familiar; easy thresholds.
Watch out: Mean and std are distorted by outliers; weak on skew.
Strengths: Reflects reality; capping keeps rows.
Watch out: Needs domain knowledge; capping changes the distribution.
Interview signals & numbers to know
When this topic comes up
- “Revenue doubled after the export”
- “How do you detect outliers?”
- “Should you always remove outliers?”
- Fraud or rare-event data
- Data quality checks
Benchmarks & rules of thumb
- 1.5 × IQR
- standard fence multiplier
- ±3
- common z-score threshold
- 1st / 99th
- typical capping percentiles
Common mistakes & follow-ups
Common interview mistakes
- Using
drop_duplicates()on all columns when retries differ only by timestamp, leaving duplicates in place. - Removing outliers that were actually the fraud cases the model was meant to find.
- Applying a z-score rule to a heavily skewed column and flagging a quarter of the data.
Likely interviewer follow-ups
- How would you choose which duplicate to keep?
- Why might removing outliers hurt a fraud model?
- When would you cap values instead of removing them?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Duplicate Removal & Outlier Detection with data science interview Q&A and hands-on practice.