Overview
Sort the values. A quarter of them lie below the first quartile, half below the second (the median) and three quarters below the third. The distance from the first to the third is the interquartile range, or IQR: the width of the middle half of the data. Because it looks only at the middle, a wild value at either end does not change it, unlike the standard deviation. Tukey's rule uses the IQR as a yardstick: a value more than 1.5 IQRs outside the quartiles is flagged as an outlier. On small samples the exact position of a quartile is a matter of convention, so the rule for finding it is a parameter.
A short history
Quartiles came into use in the nineteenth century; Francis Galton relied on them and on the semi interquartile range to describe human measurements in the 1880s. John Tukey gave them their modern role in his 1977 book Exploratory Data Analysis, where the five number summary and the fences at 1.5 times the interquartile range beyond the quartiles became a simple, robust way to describe spread and to flag possible outliers.
How it works
- Sort the values.
- For each quartile level (0.25, 0.5, 0.75), compute a position in the sorted data from the configured rule.
- If the position falls between two values, interpolate linearly between them.
- With the tukey method, take instead the median of the lower half and of the upper half of the data. For an odd count the overall median belongs to both halves.
- Subtract the first quartile from the third to get the IQR.
- Set the fences at fence times the IQR below the first quartile and above the third.
- Flag every value outside the fences. NaN is never flagged.
Watch out for
- On strongly skewed data the rule flags much of the long tail, because the fences sit at the same distance on both sides of a bulk that is not symmetric.
- On data with several peaks, values lying between the peaks are inside the fences and are missed, even if they are unusual.
- Different quantile rules give slightly different quartiles on small samples, so results from two tools may not match unless the method matches.
- A flagged value is unusual by this yardstick, not wrong. Removing flagged values without checking them can delete the most informative rows.
- If more than half the values are identical, the IQR can be zero. Then the fences collapse onto the quartiles and every different value is flagged.
Use cases
When to use it
For skewed or heavy-tailed columns where the standard deviation misleads, and as a quick outlier screen that assumes little before modelling.
In industry
- Data cleaning
- Analysts flag sensor readings or transaction amounts outside the Tukey fences for review before they distort averages or model training.
- Education
- Test results are reported in quartiles so that a school or student can be placed in the bottom, middle or top quarter of a reference group.
- Healthcare
- Skewed measures such as length of hospital stay are reported as a median with an interquartile range.
Choosing it: what must hold
- A numeric or at least ordinal variable.
- Enough observations for quartiles to be meaningful, since with very few points they depend on the interpolation rule.
- Acceptance that points outside the fences are candidates to inspect, not automatically errors.
When to choose something else
| If | Use instead |
|---|---|
| The data are close to normal and you need a spread that feeds further formulas | Standard deviation |
| The distribution is strongly skewed, so the fences flag a large share of valid points | A transformation first, or a method such as an isolation forest |
| Outliers depend on several columns together | A multivariate method such as Mahalanobis distance |
Math foundations
Position of a quantile
The position in the sorted data, counted from 1, of the quantile at level . The constant selects the rule: 1 for linear, 0 for weibull, 0.5 for hazen and 1/3 for median_unbiased. The position is clamped to the range 1 to .
Interpolated quantile
When is not a whole number, the quantile lies between two sorted values, at the fraction given by the decimal part of .
Interquartile range
The width of the middle half of the data. Up to a quarter of the values at each end can be moved further out without changing it.
Tukey's fences
Values below or above are flagged. The usual is 1.5 for an outlier and 3 for a far outlier.
What the rule means for normal data
For a normal distribution the quartiles sit 0.6745 standard deviations from the mean, so the fences land near 2.7 standard deviations. About 0.7 percent of normal values fall outside them.
Symbols
- the j-th smallest value of the sample
- number of values
- the quantile level, between 0 and 1
- the plotting-position constant of the chosen quantile rule
- position of the quantile in the sorted data, counted from 1
- first and third quartiles
- the fence multiple (config fence, default 1.5)
- mean and standard deviation of a normal distribution
Worked by hand
Nine values, sorted: -40, 1, 2, 3, 4, 5, 6, 7, 50. Use the linear rule (), so , and .
The values -40 and 50 lie outside the fences and are flagged. Making them -4000 and 5000 would not change the quartiles, the IQR or the fences.
Visual example
Loading the example.
Try this
- Drag the value at 90 all the way to 100, then back to 30: nothing in the readout moves until it changes rank.
- Slide the quantile level p and watch h travel between two positions in the top row.
- Switch the quantile rule and see the quartile positions shift a little while the data stay put.
Code sample
from impl import Quartiles
from config import QuartilesConfig
q = Quartiles(QuartilesConfig(method="linear", fence=1.5))
x = [50, 3, 1, 2, 4, 5, 7, 6, -40]
print(q.quartiles(x)) # (2.0, 4.0, 6.0)
print(q.fences(x)) # (-4.0, 12.0)
print(q.outliers(x)) # [ 50. -40.]
print(q.summary(x))Read the implementation (102 lines)
"""Quartiles, the interquartile range and IQR-based outlier detection.
NumPy only. Quantiles are computed here from first principles: the sorted sample is indexed at the (1-based)
position a + p * (n + 1 - 2a) and neighbouring values are interpolated linearly. The constant `a` is what the
named rules differ in. Tukey's hinges are the medians of the lower and upper halves of the data.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import QuartilesConfig
except ImportError: # run from the template's own folder
from config import QuartilesConfig
# Plotting-position constant of each interpolating rule (Hyndman and Fan types 7, 6, 5 and 8).
_POSITION = {"linear": 1.0, "weibull": 0.0, "hazen": 0.5, "median_unbiased": 1.0 / 3.0}
def _median_sorted(s: np.ndarray) -> float:
middle = s.size // 2
return float(s[middle]) if s.size % 2 else float(0.5 * (s[middle - 1] + s[middle]))
class Quartiles:
"""Quartiles, IQR, fences and outlier flags of a numeric sample."""
def __init__(self, config: QuartilesConfig | None = None) -> None:
self.config = config or QuartilesConfig()
@staticmethod
def _sorted(values) -> np.ndarray:
x = np.asarray(values, dtype=float).ravel()
x = np.sort(x[~np.isnan(x)])
if x.size == 0:
raise ValueError("values holds no numbers")
return x
def quantile(self, values, p: float) -> float:
"""The p-quantile (0 <= p <= 1) of values, shape (n,), by the configured interpolating rule."""
if not 0.0 <= p <= 1.0:
raise ValueError(f"p must be in [0, 1], got {p}")
if self.config.method == "tukey":
raise ValueError("the tukey method defines only the three quartiles; use quartiles()")
s = self._sorted(values)
n = s.size
a = _POSITION[self.config.method]
position = min(max(a + p * (n + 1.0 - 2.0 * a), 1.0), float(n)) # 1-based, clamped to the data
below = int(math.floor(position))
fraction = position - below
upper = s[min(below, n - 1)]
return float(s[below - 1] + fraction * (upper - s[below - 1]))
def quartiles(self, values) -> tuple[float, float, float]:
"""(Q1, Q2, Q3): the values below which 25 %, 50 % and 75 % of the data lie."""
if self.config.method != "tukey":
return self.quantile(values, 0.25), self.quantile(values, 0.5), self.quantile(values, 0.75)
s = self._sorted(values)
half = (s.size + 1) // 2 # for an odd count the median belongs to both halves
return _median_sorted(s[:half]), _median_sorted(s), _median_sorted(s[s.size - half:])
def iqr(self, values) -> float:
"""Interquartile range Q3 - Q1: the width of the middle half of the data."""
q1, _, q3 = self.quartiles(values)
return q3 - q1
def fences(self, values) -> tuple[float, float]:
"""(lower, upper) = (Q1 - fence * IQR, Q3 + fence * IQR)."""
q1, _, q3 = self.quartiles(values)
spread = self.config.fence * (q3 - q1)
return q1 - spread, q3 + spread
def outlier_mask(self, values) -> np.ndarray:
"""Boolean array of the input's shape: True where a value lies outside the fences. NaN is never flagged."""
x = np.asarray(values, dtype=float)
lower, upper = self.fences(x)
with np.errstate(invalid="ignore"):
return (x < lower) | (x > upper)
def outliers(self, values) -> np.ndarray:
"""The flagged values, in their original order."""
x = np.asarray(values, dtype=float)
return x[self.outlier_mask(x)]
def summary(self, values) -> dict:
"""min, q1, median, q3, max, iqr, both fences and the number of outliers."""
s = self._sorted(values)
q1, q2, q3 = self.quartiles(s)
lower, upper = self.fences(s)
return {
"min": float(s[0]),
"q1": q1,
"median": q2,
"q3": q3,
"max": float(s[-1]),
"iqr": q3 - q1,
"lower_fence": lower,
"upper_fence": upper,
"n_outliers": int(self.outlier_mask(s).sum()),
}- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Call quartiles, fences and outliers on the nine values above with Quartiles(QuartilesConfig(method="linear")). Repeat with method set to weibull and to tukey and compare the quartiles. Then set fence to 3.0 and see which values are still flagged.
Check on learning
- The standard deviation of the nine values in the worked example is about 23, yet seven of them lie within 3 of the median. Which measure describes the data better, and why do the two disagree?
A way to think about it
Look at how much of the sum of squares comes from the two extreme values, and at whether they enter the IQR at all.
- Apply the 1.5 rule to waiting times that follow a long right tail. Many points are flagged on the high side and none on the low side. Are those points errors?
A way to think about it
The rule assumes a symmetric bulk. Think about whether a transformation or a different yardstick fits data that are skewed by nature.
- Why do the linear and weibull rules give different quartiles for 9 values but nearly identical ones for 9000?
A way to think about it
Compare the positions under and . The gap between them is a fixed fraction of a step, and a step between sorted values shrinks as grows.
- In a sample of a million normal values, roughly how many does the 1.5 rule flag, and what does that say about treating every flagged value as an anomaly?
A way to think about it
Use the 0.7 percent figure. A fixed yardstick flags a fixed share, so the count grows with the sample.
- A sensor reports 0 for 80 percent of readings and real values otherwise. What happens to the IQR and the fences, and how would you screen this column instead?
A way to think about it
Find and when most values are the same. Consider screening the non-zero readings on their own.