Working With Data Guide 3 of 8 · tap to switch
Missing Data and Outliers
How to handle blank spreadsheet cells, catch outliers without falling for the Z-score masking trap, and tell typos apart from real signal.
Clean textbook CSV files barely exist outside university homework. Real datasets arrive with blank cells, broken sensors, duplicated exports, and impossible typos. Spending twenty minutes cleaning your table often boosts model performance more than switching algorithms ever could. Knowing how to diagnose missing data and outliers safely before modeling prevents silent errors downstream.
Start with blank cells (missing values). Spreadsheets and machine learning tools mark an empty numeric cell as NaN (short for Not a Number). Most models cannot run math on a NaN, so you either drop that row or use imputation: filling each blank cell with a sensible stand-in number, such as the column’s median (the middle value when sorted).
Suppose a clinic asks ten patients to report their household income, and the three highest-risk patients leave that optional box blank. Click through Drop Rows, Fill With Mean, and Median + Missing Flag below to see what each choice quietly does to your dataset.
| Patient | Age | Income (£k) | Risk Group |
|---|---|---|---|
| Row 1 | 29 | £34k | Low |
| Row 2 | 35 | £42k | Low |
| Row 3 | 41 | £48k | Low |
| Row 4 | 46 | £55k | Low |
| Row 5 | 52 | NaN (row dropped) | Elevated |
| Row 6 | 38 | £39k | Low |
| Row 7 | 61 | NaN (row dropped) | Elevated |
| Row 8 | 33 | £46k | Low |
| Row 9 | 58 | NaN (row dropped) | Elevated |
| Row 10 | 44 | £51k | Low |
Notice the power of adding one extra 0/1 column (Income Missing? Flag): instead of pretending those three blanks never happened, your model gets to learn from the missingness itself. Always compute your fill-in median strictly from your Practice (Training) rows only, then reuse that same number on unseen Test rows so future test answers never leak in.
Catching outliers: why Z-score gets tricked (the masking trap)
Now look at extreme numbers (outliers) sitting far outside the pack in a bakery’s daily checkout log. Two classic rulers compete in almost every data workflow:
- The Average-and-Spread Ruler (Z-Score): First compute the column’s average (mean) and its standard deviation, written with the Greek letter
σ(the typical distance points sit from the average). Any day sitting more than2.5or3steps ofσpast the average (±2.5σor±3σ) gets flagged. - The Middle-Half Ruler (Tukey IQR Fence): Line up all days from lowest to highest. Find the 25% mark (
Q1) and the 75% mark (Q3). The width of that middle half,Q3 - Q1, is theIQR(middle-half spread). Anything sitting more than1.5 × IQRpastQ3(or belowQ1) gets flagged.
Follow the two steps inside the lab below: first inject the giant £2,900 scanner typo, then flip between Average ± 2.5 SD Fence and Middle-Half Fence (1.5× IQR) to watch the giant typo blind the Z-Score ruler completely.
Because the average (mean) and standard deviation (σ) pull violently toward any single extreme number, one massive typo stretches the Z-Score fence so wide that it masks (hides) the suspicious £760 day sitting right beside it. Because Q1 and Q3 look only at the middle half of the sorted list and ignore the outer ends, the middle-half (IQR) fence stays calm and catches both extremes.
Should you delete an outlier? Ask where it came from
Flagging an extreme number only starts the conversation. Automatically deleting every flagged row is one of the worst habits in applied machine learning, because an extreme value can mean three completely different things:
- An impossible data-entry typo (like a patient listed as 240 years old), which should be marked blank (
NaN) and filled cleanly with the median. - A real rare signal (like a genuine $250k VIP order or a high-value credit card fraud alert), which you must keep (and put on a log scale if numbers span orders of 10) because those rare spikes are often the exact event you care about predicting.
- A true one-off disruption (like a 180-minute blizzard delay), where capping extreme spikes at a sensible ceiling (like the 99th percentile) or training with an outlier-resistant error rule keeps one freak day from ruining everyday estimates.
Test all three real-world cases below and toggle between the broken move and the right fix to watch the chart react live.
Three silent bugs that never throw a Python error
Your code can run cleanly with zero warnings while silently training on garbage. Machine learning tools only recognize true blank cells (NaN) as missing data: they never guess that -999 means blank, they never notice that two branches logged pounds and kilograms in the same column, and they never warn you if duplicate customer rows leaked into your Test set.
Inspect the three live 5-row spreadsheets below, starting in their broken raw state, then click Apply Cleanup Fix to see how each silent bug distorts your averages and test scores.
| Row | Patient | Age | Blood Pressure (mmHg) | How the Model Reads It |
|---|---|---|---|---|
| #1 | P-101 | 34 | 96 | Normal reading |
| #2 | P-102 | 52 | -999 | Treated as a real negative pressure! |
| #3 | P-103 | 41 | 100 | Normal reading |
| #4 | P-104 | 63 | 103 | Normal reading |
| #5 | P-105 | 29 | 100 | Normal reading |
See Rubin's missingness taxonomy (MCAR/MAR/MNAR) & Modified Z-ScoreThesis / Reference
1. Rubin’s Missing-Data Mechanisms (Little & Rubin, 2002): Let denote the binary missingness mask and :
- MCAR (Missing Completely at Random): . Dropping rows is unbiased, though it reduces statistical power.
- MAR (Missing at Random): . Missingness depends on other observed columns (e.g. older patients skipping an online form). Dropping rows biases estimates; model-based imputation (MICE / IterativeImputer) recovers unbiased estimates.
- MNAR (Missing Not at Random): depends on the unobserved missing value itself (e.g. high earners hiding income). Adding a missingness indicator column is critical for predictive models.
2. Tukey IQR Fence & Iglewicz-Hoaglin Modified Z-Score: Standard Z-score has a 0% breakdown point. Both Tukey’s fence and the MAD-based Modified Z-Score achieve a 50% breakdown point:
Here scales to match for Normal data. For multivariate outliers (rows where every single column looks normal alone, yet their combination is bizarre, like a 10 m² mansion with 6 bedrooms), use Mahalanobis distance or Isolation Forests.
See leak-free imputation + missing flags in PythonOptional Code
import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import Ridge
# Convert hidden -999 sentinel codes to real NaN first
X_train = np.where(X_train == -999, np.nan, X_train)
X_test = np.where(X_test == -999, np.nan, X_test)
# Fit median imputer on Train ONLY, and auto-append binary missingness flags!
pipe = make_pipeline(
SimpleImputer(strategy="median", add_indicator=True),
Ridge(alpha=1.0),
)
pipe.fit(X_train, y_train)Next step: turning text categories into safe numbers
Your numeric columns are now clean, inspected, and leak-free. What about text columns like "Hackney", "Camden", "Card", or "Small / Medium / Large"? Next up in Categorical Encoding, we see how to turn text into numbers without tricking your model into fake math.
Quick Intuition Check
Four quick real-world scenarios. No scores, just test your intuition.
In a loan application dataset, 25% of applicants left the 'previous bankruptcy year' column blank (mostly people who never went bankrupt). What is the safest way to handle those blanks?
A single £50,000 scanner typo enters a column of £300 daily sales. Why might a standard Z-score detector suddenly fail to flag a genuine £900 anomaly?
You are building a credit card fraud detector and discover 15 transactions over £10,000 sitting far outside the IQR fence. What should you do?
If an old hospital database records unknown patient ages as -999 instead of leaving the cell blank, standard machine learning tools automatically recognize -999 as missing data without being told.
Common Questions
Should I drop rows with missing values or impute them?
Why add a binary missingness indicator column (like income_was_missing)?
Why is the IQR method often better than Z-score for detecting outliers?
Should I always delete outliers before training a machine learning model?
When should I fit my missing-value imputer?
Related Visual Guides
Linear Regression
How a machine learns to draw the best prediction line from real examples, and when that line can be fooled.
Feature Scaling: Normalization vs Standardization
Why salary in pounds bullies age in years, how Min-Max, Standardization, and RobustScaler compare under outliers, and which models actually care.
Descriptive Statistics
How to read any dataset in minutes: data types, mean vs. median, standard deviation, IQR box plots, and why averages alone can mislead.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@misc{irshad2026dataqualityoutliers,
author = {Irshad, Muhammad Aashir},
title = {Missing Data and Outliers: Interactive Visual Guide},
howpublished = {SeeingML},
year = {2026},
month = {dec},
url = {https://seeingml.com/learn/data-quality-outliers/},
note = {Interactive visual guide}
} Irshad, M. A. (2026). Missing Data and Outliers: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/data-quality-outliers/