1. Numerical Computing & Vectorized Thinking
Descriptive Statistics, Percentiles & Outlier Detection
Summarize datasets accurately without getting fooled by extreme values: compare mean vs median, compute standard deviation and IQR percentiles, and flag outliers using Python's statistics module.
- Choose accurately between mean and median when data is skewed by outliers
- Measure spread using standard deviation and Interquartile Range (IQR)
- Detect statistical outliers cleanly with Z-scores and the 1.5 * IQR rule
Suppose you are on-call for an e-commerce checkout API. Most requests finish in 45 ms to 65 ms, so users think the site is snappy—except 2% of requests hit an unindexed database query and stall for 950 ms. If your dashboard only prints the average (mean) latency, that spike hides behind the crowd, or pulls the average up so much that normal requests look slow too.
Before building charts or training models, every analyst summarizes center (what is typical) and spread (how wide values scatter). Picking the wrong summary metric is one of the fastest ways to misread business data.
1. Mean vs Median (Why Averages Can Lie)
Consider 9 learners earning $50k–$70k and 1 executive earning $950k:
- The mean (sum divided by count) jumps to
~$150k—a number that describes nobody in the room. - The median (the middle value once sorted, or the 50th percentile) stays at
~$60k—accurately reflecting the typical earner.
Decision Guide: Center & Spread Metrics
| Data Shape | Best Center Metric | Best Spread Metric | Typical Real-World Examples |
|---|---|---|---|
| Symmetric / Bell-shaped | Mean | Standard Deviation (stdev) | Sensor temperatures, manufacturing weights, exam scores |
| Right- or Left-Skewed | Median (P50) | IQR (Q3 - Q1) | Incomes, home prices, order totals, API response latencies |
| Tail / SLA Monitoring | Median (P50) | P95 & P99 percentiles | Web page load times, checkout latencies, delivery delays |
Compare mean and median in df.describe():
- If
meanis much larger thanmedian, you have right skew (a few huge high values pulling the average up). - If
meanis roughly equal tomedian, the distribution is fairly symmetric.
2. Quantiles, Percentiles & The 1.5 * IQR Outlier Rule
The box captures the middle 50% of values (Q1 to Q3). Any point beyond Q3 + 1.5 × IQR is flagged as a statistical outlier.
Percentiles sort your dataset from lowest to highest and slice it into 100 equal parts:
- P25 (
Q1): 25% of values fall below this point. - P50 (
Q2/ Median): 50% of values fall below this point. - P75 (
Q3): 75% of values fall below this point. - IQR (Interquartile Range):
IQR = Q3 - Q1, capturing the spread of the middle 50% of your data while completely ignoring extreme outliers at either end. - P95 / P99: Essential for engineering SLAs—"99% of checkout requests finish under 240 ms."
Step-by-Step: Computing IQR Fences
Because Q1, Q3, and IQR ignore extreme spikes, they give us a rock-solid boundary for flagging anomalies (this is also how boxplots draw their whiskers):
- Sort the numbers and find
Q1(25th percentile) andQ3(75th percentile). - Compute
IQR = Q3 - Q1. - Compute the lower fence:
Q1 - 1.5 * IQR. - Compute the upper fence:
Q3 + 1.5 * IQR. - Any observation outside
[lower_fence, upper_fence]is flagged as an outlier.
When to Use 1.5 * IQR vs Z-Score
A Z-score measures how many standard deviations a point sits from the mean: z = (x - mean) / stdev. Anything with abs(z) > 3 is often treated as an outlier—but only when data is roughly bell-shaped.
When a dataset has one extreme spike (like a $50,000 wholesale order among $40 retail orders), that single spike inflates both mean and stdev so much that its own Z-score can drop below 3.0—hiding the very outlier you wanted to catch! The 1.5 * IQR rule does not get distorted by extreme tails.
3. Computing Percentiles & IQR in Pandas
In real DataFrame workflows, you don't need manual loops—Pandas computes every quantile and IQR fence vectorially in three lines:
q1 = df["latency_ms"].quantile(0.25)
q3 = df["latency_ms"].quantile(0.75)
iqr = q3 - q1
p95 = df["latency_ms"].quantile(0.95)
upper_fence = q3 + 1.5 * iqr
outliers = df.loc[df["latency_ms"] > upper_fence]4. Never Blindly Delete Outliers
Flagging an outlier is the start of an investigation, not an automatic delete button. Outliers fall into two very different buckets:
- Data bugs / sensor glitches: A negative age (
-5), a999999placeholder, or a$0.01test order. Filter or quarantine these. - Real high-impact events: A Black Friday enterprise purchase or a 950 ms database deadlock. Deleting real outliers erases your biggest business risks and revenue drivers—keep them in totals, and report median alongside mean!
Try It Yourself in the Playground
Python's built-in statistics module provides mean, median, stdev, and quantiles directly on any sequence of numbers. Inspect how two latency spikes distort mean and stdev while median and IQR stay steady:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Using statistics.quantiles(data, n=100), how do you read the 95th percentile (P95) of a list data? (Hint: quantiles(..., n=100) returns 99 cut points, where index 0 is P1 and index 94 is P95.)
Quick Checkpoints
You are analyzing e-commerce order totals where most orders are $20–$80, but a few wholesale orders are $15,000. Which metric best describes a typical order?
How is the Interquartile Range (IQR) defined?
Why did the Z-score fail to flag the 420 ms spike in the Playground example above (z < 3.0)?