Median
The median is the middle value of the data once it is sorted. Half of the observations are at or below it, and half are at or above it. It is the 50th percentile, also called the second quartile (Q2).
Finding the median by hand
- Sort the values.
- If
nis odd, the median is the value at position(n + 1) / 2. - If
nis even, the median is the mean of the two middle values, at positionsn / 2andn / 2 + 1.
def median(values):
s = sorted(values)
n = len(s)
mid = n // 2
if n % 2 == 1:
return s[mid]
return (s[mid - 1] + s[mid]) / 2
odd = [7, 3, 9, 1, 5] # sorted: 1 3 5 7 9
even = [7, 3, 9, 1, 5, 11] # sorted: 1 3 5 7 9 11
print("odd n :", sorted(odd), "->", median(odd))
print("even n:", sorted(even), "->", median(even))odd n : [1, 3, 5, 7, 9] -> 5
even n: [1, 3, 5, 7, 9, 11] -> 6.0
Python's indexes start at 0, so for odd n the middle element is at index n // 2.
With the statistics module
The module offers three variants that differ only for even n:
import statistics
prices = [12, 15, 18, 20]
print("median :", statistics.median(prices))
print("median_low :", statistics.median_low(prices))
print("median_high :", statistics.median_high(prices))median : 16.5
median_low : 15
median_high : 18
median_low and median_high always return an actual data value, which is useful when averaging two values makes no sense (e.g. for ordinal codes).
The median resists outliers
Back to the 40 commute times from Frequency Tables. Suppose a typo turns one 28-minute commute into 280:
import statistics
commute = [22, 35, 18, 41, 27, 30, 25, 52, 33, 29, 19, 24, 38, 31, 27, 45, 23, 28, 36, 26,
21, 34, 30, 58, 27, 32, 25, 29, 40, 24, 17, 31, 28, 37, 26, 33, 22, 30, 47, 28]
typo = commute[:-1] + [280]
print(f"correct data: mean={statistics.mean(commute):.2f} median={statistics.median(commute)}")
print(f"with a typo : mean={statistics.mean(typo):.2f} median={statistics.median(typo)}")correct data: mean=30.70 median=29.0
with a typo : mean=37.00 median=29.5
The single typo moved the mean by more than six minutes but the median by only half a minute (the typo merely swapped which values sit in the middle). That robustness is why medians are reported for incomes, house prices and response times.
Median of a frequency table
When data comes as a frequency table, find the value where the cumulative frequency first reaches half of n. Customer ratings of a hotel:
import numpy as np
stars = np.array([1, 2, 3, 4, 5])
count = np.array([8, 12, 30, 61, 39])
n = count.sum()
cumulative = np.cumsum(count)
print("n =", n, " cumulative:", cumulative.tolist())
idx = np.searchsorted(cumulative, n / 2) # first position where cum >= n/2
print("median rating:", stars[idx], "stars")
# check by expanding the table into raw values
print("check:", np.median(np.repeat(stars, count)))n = 150 cumulative: [8, 20, 50, 111, 150]
median rating: 4 stars
check: 4.0
Medians by group in pandas
import pandas as pd
homes = pd.DataFrame({
"district": ["Old Town", "Old Town", "Old Town", "Harbour", "Harbour", "Harbour", "Harbour"],
"price_k": [310, 295, 1450, 420, 390, 405, 2100],
})
summary = homes.groupby("district")["price_k"].agg(["mean", "median"]).round(1)
print(summary) mean median
district
Harbour 828.8 412.5
Old Town 685.0 310.0
In both districts one luxury property inflates the mean; the median gives a far more realistic picture of a typical home.
Test yourself
What is the median of 8, 3, 10, 5, 7?
- 5
- 6.6
- 7
- 10
What is the median of 2, 4, 6, 20?
- 5
- 6
- 8
- 4
Which function always returns a value that actually appears in the data?
statistics.medianstatistics.median_lowstatistics.meannp.median