SeeingML
Working With Data Guide 3 of 8 · tap to switch
✦ Interactive Visual Guide 8 min · 4 hands-on labs · Beginner friendly

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.

Interactive Lab 1: Handling Blank Cells (NaN) Without Deleting Signal
Watch the 3 Elevated-risk patients: all three left Income blank (NaN). Click through the three strategies above to compare what stays and what vanishes.
PatientAgeIncome (£k)Risk Group
Row 129£34kLow
Row 235£42kLow
Row 341£48kLow
Row 446£55kLow
Row 552NaN (row dropped)Elevated
Row 638£39kLow
Row 761NaN (row dropped)Elevated
Row 833£46kLow
Row 958NaN (row dropped)Elevated
Row 1044£51kLow
Rows kept: 7/10Elevated-risk patients kept: 0/3Blank-cell clue preserved: No
Dropping incomplete rows threw away 30% of the clinic table AND silently erased ALL 3 Elevated-risk patients! The surviving sample averages £45.0k instead of the true £75.5k.

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 than 2.5 or 3 steps 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 the IQR (middle-half spread). Anything sitting more than 1.5 × IQR past Q3 (or below Q1) 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.

Interactive Lab 2: Average/SD Fence vs. Middle-Half (IQR) Fence
Step 1:Add the £2,900 TypoStep 2:Compare Average/SD Fence vs. Middle-Half (IQR) Fence
Upper Fence: £681£0£200£400£600£800Daily Bakery Sales (£) · Red Ring = Flagged Outlier · Shaded Band = Considered Normal£760
Average (Mean): £407Average Spread (SD, σ): £110Upper Fence: £681Flagged: £760
Dataset scenario:
With only one £760 spike, the Average ± 2.5 SD fence (upper limit £681) catches £760 just fine. Now try Step 1: click "+ £760 & £2,900 Typo" below to see what happens when one giant scanner typo enters the same column!

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.

Interactive Lab 3: Typo vs. Real Signal (Live Mini-Experiments)
Status: Broken / Raw State
Toggle action:
110120130140150050100150200250Patient Age (Years) · Age 240 typo drags trend line the wrong way!Blood Pressure (mmHg)Warped Trend (Slopes Down!)Age 240 (Typo!)
Fitted slope: -0.03 mmHg/yrAvg error on real patients: ±9.7 mmHgOrigin: Data-entry typo (impossible age)
Broken raw value! Because Age 240 sits wildly far to the right, it yanked the red trend line downward (negative slope!), predicting lower blood pressure for older patients and inflating average error to ±9.7 mmHg. Click "Mark Blank (NaN) & Fill Median" above!

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.

Interactive Lab 4: Live 5-Row Spreadsheet Bug Fixer
Table state: Broken Raw Table
Inspect raw table, then apply cleanup:
RowPatientAgeBlood Pressure (mmHg)How the Model Reads It
#1P-1013496Normal reading
#2P-10252-999Treated as a real negative pressure!
#3P-10341100Normal reading
#4P-10463103Normal reading
#5P-10529100Normal reading
Live Impact: Computed Average Blood Pressure-120 mmHg (Impossible Negative!)
-150 mmHg0+100 mmHg (Normal)+150 mmHg
Silent bug active! Machine learning tools only treat real blank cells (NaN) as missing. Because Row #2 stores -999 as an ordinary number, Python throws zero errors while dragging average blood pressure down to -120 mmHg and wrecking model predictions. Click "Apply Cleanup Fix" above!
See Rubin's missingness taxonomy (MCAR/MAR/MNAR) & Modified Z-ScoreThesis / Reference

1. Rubin’s Missing-Data Mechanisms (Little & Rubin, 2002): Let MM denote the binary missingness mask and X=(Xobs,Xmis)X = (X_{\text{obs}}, X_{\text{mis}}):

  • MCAR (Missing Completely at Random): P(M∣X)=P(M)P(M \mid X) = P(M). Dropping rows is unbiased, though it reduces statistical power.
  • MAR (Missing at Random): P(M∣X)=P(M∣Xobs)P(M \mid X) = P(M \mid X_{\text{obs}}). 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): P(M∣X)P(M \mid X) depends on the unobserved missing value itself (e.g. high earners hiding income). Adding a missingness indicator column MjM_j is critical for predictive models.

2. Tukey IQR Fence & Iglewicz-Hoaglin Modified Z-Score: Standard Z-score zi=(xi−xˉ)/sz_i = (x_i - \bar{x})/s has a 0% breakdown point. Both Tukey’s fence and the MAD-based Modified Z-Score achieve a 50% breakdown point:

IQR Fence: [ Q1−1.5⋅IQR,    Q3+1.5⋅IQR ]\text{IQR Fence: }\left[\,Q_1 - 1.5\cdot\text{IQR},\;\; Q_3 + 1.5\cdot\text{IQR}\,\right]
Mi=0.6745 (xi−median(x))MAD,flag if ∣Mi∣>3.5M_i = \frac{0.6745\,(x_i - \text{median}(x))}{\text{MAD}}, \qquad \text{flag if } |M_i| > 3.5

Here 0.6745=Φ−1(0.75)0.6745 = \Phi^{-1}(0.75) scales MAD\text{MAD} to match σ\sigma 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
python
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.

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

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?

Pick an option first, or peek anytime
2

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?

Pick an option first, or peek anytime
3

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?

Pick an option first, or peek anytime
4

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.

Pick an option first, or peek anytime
Quick Reference

Common Questions

Should I drop rows with missing values or impute them?
Only drop rows when missingness is tiny (under 1% to 2%) and completely random. Otherwise, dropping rows shrinks your dataset and introduces severe selection bias if certain groups skip questions more often. Imputing on Train only plus adding a missingness flag preserves both rows and signal.
Why add a binary missingness indicator column (like income_was_missing)?
In real life, the fact that a field is blank often carries strong predictive information (for example, patients skipping an optional test or high earners skipping income). Adding a 0/1 indicator column lets your model learn directly from missingness itself.
Why is the IQR method often better than Z-score for detecting outliers?
Standard Z-score relies on Mean and Standard Deviation, which are themselves inflated by extreme outliers (the masking trap). Tukey's IQR fence uses Q1 and Q3, staying rock-solid even when massive data-entry typos appear.
Should I always delete outliers before training a machine learning model?
Never delete outliers automatically without investigating first. Fix or drop physically impossible typos (like age = 240), keep genuine rare events in fraud or medical detection, and cap (Winsorise) or log-transform heavy real tails.
When should I fit my missing-value imputer?
Always fit imputers (medians, means, KNN imputers) strictly inside the Training Set or inside a scikit-learn Pipeline during cross-validation so validation and test rows never leak into imputed values.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/data-quality-outliers/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@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}
}
APA

Irshad, M. A. (2026). Missing Data and Outliers: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/data-quality-outliers/