Overview
The mean is the balance point of the data: if each value were a weight on a ruler, the ruler would balance there. Every value pulls on it, so one extreme value can drag it far. The median is the middle of the sorted data, with half the values on each side. It only cares about order, so it ignores how extreme the tails are. The mode is the value that occurs most often, and it is the only one of the three that works for labels such as colours. When the mean and the median are far apart, the data are skewed, meaning one tail is longer than the other.
A short history
The arithmetic mean was used by astronomers from antiquity and became standard in the seventeenth and eighteenth centuries as a way to combine repeated observations. The median was promoted in the nineteenth century by writers such as Gustav Fechner and Francis Galton as a value that resists extreme observations. Karl Pearson coined the term mode in 1895. The three together give the usual answer to what a typical value is.
How it works
- Apply the NaN policy: drop NaN, return NaN, or raise an error.
- For the mean, add the values and divide by how many there are. With weights, multiply each value by its weight and divide by the sum of weights.
- For the median, sort the values and take the middle one. With an even count, average the two middle values.
- For the mode, count how often each value occurs and take the most frequent. Ties are returned all together, or as the smallest or first, by mode_ties.
- For a robust mean, use trimmed_mean, which cuts the lowest and highest trim fraction of the sorted values before averaging.
- Use geometric_mean for growth factors and harmonic_mean for rates.
- Call summary to get mean, median and mode together with a skew hint from the sign of mean minus median.
Watch out for
- A single extreme value can move the mean anywhere, because every value enters the sum with equal weight.
- The median ignores the size of the tails, so it hides the fact that a few values are enormous. That matters when totals count, as with costs.
- For continuous data almost every value occurs once, so the mode is arbitrary unless you group the values into bins first.
- The geometric and harmonic means need positive values. A zero or a negative number makes them undefined or meaningless.
- The skew hint compares only mean and median. It is a quick sign and can be wrong for distributions with several peaks.
Use cases
When to use it
Mean for roughly symmetric numeric data, median for skewed data or data with outliers such as incomes and durations, mode for categories. Report mean and median together, since a gap between them is the first sign of skew.
In industry
- Economics and government
- Statistical offices report median household income, not the mean, because a small number of very high incomes pulls the mean upward.
- Retail
- A clothing retailer stocks by the modal size, the size sold most often, since an average size is not something anyone buys.
- Operations
- Teams track mean handling time for capacity planning because means add up to totals, and medians to describe a typical case.
Choosing it: what must hold
- For the mean, interval or ratio data without heavy skew or extreme outliers.
- For the median, data that can at least be ordered.
- For the mode, categories or discrete values with repeats; on continuous data it needs binning first.
- A distribution with one main peak, so that a single typical value is a fair summary.
When to choose something else
| If | Use instead |
|---|---|
| The data are skewed or contain outliers and you would have used the mean | The median, or a trimmed mean |
| Values are rates or ratios, or grow multiplicatively | The harmonic or geometric mean |
| The distribution has two or more peaks | Distribution analysis, describing each group separately |
Math foundations
Arithmetic mean
The sum shared out equally. It is the one number that makes the deviations add up to zero.
Weighted mean
Each value counts in proportion to its weight. With all weights equal it reduces to the ordinary mean.
What the mean minimises
The mean is the single number closest to all the data in squared distance. Squaring punishes large gaps heavily, which is why outliers pull the mean.
What the median minimises
The median is closest in absolute distance. A far value adds only its distance, not its square, so it has much less pull.
Geometric mean
The average on a multiplicative scale. If an amount grows by factors , growing by each time gives the same end result.
Harmonic mean
The right average for rates over equal amounts of work, such as speeds over equal distances. For positive values, .
Symbols
- the i-th value
- number of values
- the weight of the i-th value
- a candidate for the typical value
- the arithmetic mean
- the geometric mean and the harmonic mean
Worked by hand
Five values: 1, 2, 2, 3, 10, already sorted. Use a trim fraction of 0.2, which cuts one value from each end.
The mean of 3.6 is larger than four of the five values, pulled up by the 10. The median and mode stay at 2. Mean above median gives the skew hint right.
Visual example
Loading the example.
Try this
- Drag the dot at 10 down to 4 and back: the mean follows it, the median stays at 2.
- Set the trim fraction to 0 and the trimmed mean becomes the plain mean.
- Add values and stack three of them on one number to move the mode.
Code sample
from impl import CentralTendency
from config import CentralTendencyConfig
c = CentralTendency(CentralTendencyConfig(trim=0.2, mode_ties="all"))
x = [1, 2, 2, 3, 10]
print(c.mean(x), c.median(x), c.mode(x)) # 3.6 2.0 [2]
print(c.trimmed_mean([1, 2, 3, 4, 100])) # 3.0
print(c.geometric_mean([1, 3, 9])) # 3.0
print(c.summary(x)["skew_hint"]) # rightRead the implementation (116 lines)
"""Central tendency: the mean (several kinds), the median and the mode.
NumPy and the standard library only. Means and medians take numeric data; the mode also takes labels.
"""
from __future__ import annotations
import math
from collections import Counter
import numpy as np
try:
from .config import CentralTendencyConfig
except ImportError: # run from the template's own folder
from config import CentralTendencyConfig
class CentralTendency:
"""One "typical value" of a sample, computed in the way that suits the data."""
def __init__(self, config: CentralTendencyConfig | None = None) -> None:
self.config = config or CentralTendencyConfig()
def _numbers(self, values, weights=None) -> tuple[np.ndarray, np.ndarray | None]:
"""Flatten to float and apply the NaN policy. Returns (values, weights), both of shape (n,)."""
x = np.asarray(values, dtype=float).ravel()
w = None if weights is None else np.asarray(weights, dtype=float).ravel()
if w is not None and w.size != x.size:
raise ValueError(f"weights must match values in length, got {w.size} and {x.size}")
missing = np.isnan(x)
if missing.any():
if self.config.nan_policy == "raise":
raise ValueError("values holds NaN")
if self.config.nan_policy == "omit":
x, w = x[~missing], (None if w is None else w[~missing])
if x.size == 0:
raise ValueError("values holds no numbers")
return x, w
def mean(self, values, weights=None) -> float:
"""Arithmetic mean sum(w * x) / sum(w). values: any shape, flattened. weights: same size, optional."""
x, w = self._numbers(values, weights)
if w is None:
return float(x.mean())
if (w < 0).any() or w.sum() == 0:
raise ValueError("weights must be non-negative and not all zero")
return float((w * x).sum() / w.sum())
def trimmed_mean(self, values) -> float:
"""Mean after dropping the lowest and highest config.trim fraction of the values (robust to outliers)."""
x, _ = self._numbers(values)
if np.isnan(x).any():
return float("nan")
x = np.sort(x)
cut = int(self.config.trim * x.size)
return float(x[cut:x.size - cut].mean())
def geometric_mean(self, values) -> float:
"""exp(mean(log x)): the right average for growth rates and ratios. All values must be positive."""
x, _ = self._numbers(values)
if (x <= 0).any():
raise ValueError("the geometric mean needs positive values")
return float(np.exp(np.log(x).mean()))
def harmonic_mean(self, values) -> float:
"""n / sum(1 / x): the right average for rates over equal distances. All values must be positive."""
x, _ = self._numbers(values)
if (x <= 0).any():
raise ValueError("the harmonic mean needs positive values")
return float(x.size / (1.0 / x).sum())
def median(self, values) -> float:
"""Middle value of the sorted data; the mean of the two middle values when the count is even."""
x, _ = self._numbers(values)
if np.isnan(x).any():
return float("nan")
x = np.sort(x)
middle = x.size // 2
return float(x[middle]) if x.size % 2 else float(0.5 * (x[middle - 1] + x[middle]))
def mode(self, values):
"""Most frequent value. values: a sequence of numbers or labels; None and NaN are skipped.
Returns a sorted list of every tied mode when config.mode_ties is "all", otherwise a single value
("smallest": the lowest tied value, "first": the tied value seen first).
"""
items = [v.item() if isinstance(v, np.generic) else v for v in np.asarray(values, dtype=object).ravel()]
items = [v for v in items if v is not None and not (isinstance(v, float) and math.isnan(v))]
if not items:
raise ValueError("values holds no data")
counts = Counter(items)
top = max(counts.values())
tied = [v for v, c in counts.items() if c == top] # Counter keeps first-seen order
if self.config.mode_ties == "first":
return tied[0]
if self.config.mode_ties == "smallest":
return min(tied)
return sorted(tied)
def summary(self, values) -> dict:
"""mean, median, mode, trimmed_mean and n of a numeric sample, plus the sign of mean minus median.
"skew_hint" is "right" when the mean exceeds the median (a long right tail pulls the mean up), "left" when
it is below, "symmetric" when they are equal.
"""
x, _ = self._numbers(values)
mean, median = self.mean(x), self.median(x)
hint = "symmetric" if math.isclose(mean, median, abs_tol=1e-12) else ("right" if mean > median else "left")
return {
"n": int(x.size),
"mean": mean,
"median": median,
"mode": self.mode(x),
"trimmed_mean": self.trimmed_mean(x),
"skew_hint": hint,
}- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 10, run with
python3 -m unittest -v
Practice
Create CentralTendency(CentralTendencyConfig(trim=0.2)) and call mean, median, mode and trimmed_mean on the five values above. Replace the 10 by 1000 and repeat, noting which results move. Then compute geometric_mean on the growth factors 1.10, 1.50 and 0.60 and compare it with their arithmetic mean.
Check on learning
- A company reports a mean salary of 90 000 and a median of 52 000. What does the gap tell you about the salaries, and which number would a typical employee recognise?
A way to think about it
Ask what kind of values pull the mean up without moving the middle of the sorted list.
- An investment grows by 50 percent one year and falls by 50 percent the next. The arithmetic mean of the changes is zero. Did the investor break even?
A way to think about it
Multiply the growth factors 1.5 and 0.5, then take the geometric mean. Compare it with 1.
- You drive 60 km at 30 km/h and return at 60 km/h. Why is your average speed not 45 km/h?
A way to think about it
Average speed is total distance over total time. You spend longer at the slow speed, which is what the harmonic mean accounts for.
- Why does the median minimise the sum of absolute distances? Think about moving the candidate value a little to the right.
A way to think about it
Each value to the left gets one step further and each value to the right one step closer. The total stops falling when the two sides are equal in number.
- When is the mean the right choice even though the data are skewed and full of outliers?
A way to think about it
Think of budgeting. The total cost is the mean times the count, and the median cannot recover a total.