The Median
Descriptive Statistics
The Value That Splits Your Data Exactly in Half
The median is the middle value of a dataset when sorted. It divides the distribution exactly in half — 50% below, 50% above.
- Robust to outliers — One extreme value cannot pull the median away from center
- Works for ordinal data — The mean cannot; the median can
- Minimizes absolute deviations — The mathematically optimal center for absolute loss
- Income, housing, and skewed data — The median tells the truth when the mean lies
When data is skewed or contaminated with outliers, the median is your most honest summary.
What You'll Learn
- 1Locate the median by position for odd and even sample sizes
- 2Explain the median's 50% breakdown point and contrast it with the mean
- 3Estimate the median of grouped data with the interpolation formula
- 4Decide between mean and median from the shape and measurement level of the data
What is the Median?
Definition
The median is the middle value of a dataset when sorted in ascending order. It divides the distribution exactly in half — 50% of values fall below, 50% above.
Calculation
For odd n: Median = the middle value (position (n+1)/2)
For even n: Median = average of the two middle values
Sorting is the whole algorithm: order the observations, then read the middle. The two cases exist because an even sample has no single middle position. For the median sits at position , the fourth smallest value. For the middle lies between positions 4 and 5, so the median becomes their average — a number that may not exist in the dataset at all. That is not a defect: the median is a functional of the distribution, not necessarily an observation.
import numpy as np
import pandas as pd
from scipy import stats
# Odd n
data_odd = [3, 7, 12, 8, 5, 15, 9]
sorted_odd = sorted(data_odd)
print(f"Sorted: {sorted_odd}")
print(f"n = {len(sorted_odd)} (odd)")
middle_pos = (len(sorted_odd) + 1) // 2
print(f"Middle position: {middle_pos}")
print(f"Median = {sorted_odd[middle_pos - 1]}")
print(f"NumPy confirms: {np.median(data_odd)}")
# Even n
data_even = [3, 7, 12, 8, 5, 15, 9, 11]
sorted_even = sorted(data_even)
print(f"\nSorted: {sorted_even}")
print(f"n = {len(sorted_even)} (even)")
n = len(sorted_even)
lower_mid = sorted_even[n//2 - 1]
upper_mid = sorted_even[n//2]
print(f"Two middle values: {lower_mid} and {upper_mid}")
print(f"Median = ({lower_mid} + {upper_mid})/2 = {(lower_mid + upper_mid)/2}")
print(f"NumPy confirms: {np.median(data_even)}")
How software interpolates
The even-sample average is one convention, and libraries expose others. np.percentile accepts method='linear' (the default, which interpolates between the two middle values), 'lower', 'higher', 'nearest' and 'midpoint'. R's median matches NumPy's default, while some survey packages report the lower observation instead. The disagreement vanishes only as grows, so record the convention whenever a median of a small sample is published.
Robustness to Outliers
The reason is structural: the median depends only on the rank of each observation, never on its magnitude. Pushing the largest value from 100 to 10,000,000 changes which position holds it but not which value occupies the middle. Formally, the median has a 50% breakdown point: contamination must exceed half the sample before the breakdown point is breached and the median can be dragged anywhere. The mean has a breakdown point of zero, so a single observation can shift it without limit.
import matplotlib.pyplot as plt
np.random.seed(42)
# Compare sensitivity to outliers
base_data = np.random.normal(50, 5, 100)
# Add increasingly extreme outliers
multipliers = [1, 2, 5, 10, 50, 100, 1000]
means = []
medians = []
for mult in multipliers:
data_with_outlier = np.append(base_data, 50 * mult)
means.append(np.mean(data_with_outlier))
medians.append(np.median(data_with_outlier))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
outlier_values = [50 * m for m in multipliers]
ax1.plot(outlier_values, means, 'r-o', label='Mean')
ax1.plot(outlier_values, medians, 'b-o', label='Median')
ax1.set_xlabel('Outlier Value')
ax1.set_ylabel('Statistic Value')
ax1.set_title('Effect of Outlier on Mean vs Median')
ax1.legend()
ax1.set_xscale('log')
# Show breakdown point
print("Breakdown point of median: 50%")
print("Breakdown point of mean: 0% (any single outlier affects it)")
print("\nWith outlier = 50000:")
data_extreme = np.append(base_data, 50000)
print(f"Mean = {np.mean(data_extreme):.2f} (was ~50)")
print(f"Median = {np.median(data_extreme):.2f} (barely changed!)")
Robustness is not free. The median discards magnitude information, so it is less efficient than the mean on perfectly normal data: the asymptotic variance of the sample median is about 1.57 times that of the sample mean, meaning you need roughly 57% more observations to match the mean's precision. The trade is worth it whenever the tail behaviour is unknown.
Why the Median Minimizes Absolute Deviations
The median is the unique value that minimizes , which makes it the natural centre for mean absolute error loss. The argument is countable: move upward past an observation and the sum changes by (number of points below) minus (number of points above), so the total can only stop decreasing once the two counts balance — exactly the median's defining property.
Median for Grouped Data
Grouped or binned data hides the individual values, so the median is recovered by assuming the observations are spread evenly inside the median class: is the lower boundary of that class, the cumulative frequency before it, its own frequency, and the class width. The result is an estimate, and its accuracy depends entirely on how well the uniformity assumption holds inside the bin.
# Frequency table
freq_table = pd.DataFrame({
'Class': ['20-29', '30-39', '40-49', '50-59', '60-69'],
'f': [5, 12, 20, 18, 5]
})
freq_table['cum_f'] = freq_table['f'].cumsum()
n = freq_table['f'].sum()
print(f"Total n = {n}, n/2 = {n/2}")
print(freq_table)
# Find median class (where cumulative frequency first exceeds n/2)
median_class_idx = (freq_table['cum_f'] >= n/2).idxmax()
print(f"\nMedian class: {freq_table.loc[median_class_idx, 'Class']}")
L = 39.5 # real lower boundary of the 40-49 class
F = freq_table.loc[median_class_idx - 1, 'cum_f'] # cumulative frequency BEFORE
f = freq_table.loc[median_class_idx, 'f']
h = 10 # class width
median_grouped = L + ((n/2 - F) / f) * h
print(f"Estimated median = {L} + ({n/2} - {F}) / {f} x {h} = {median_grouped:.2f}")
Quartiles: Generalizing the Median
data = np.random.normal(70, 15, 200)
q1, q2, q3 = np.percentile(data, [25, 50, 75])
iqr = q3 - q1
print(f"Q1 (25th pct): {q1:.2f}")
print(f"Q2 / Median: {q2:.2f}")
print(f"Q3 (75th pct): {q3:.2f}")
print(f"IQR = Q3 - Q1: {iqr:.2f}")
The family shares the median's robustness: every quantile is an order statistic, so quartiles, deciles and percentiles all ignore the magnitude of extreme values. Together the five-number summary (minimum, Q1, median, Q3, maximum) is the standard compact description of a distribution, and it is what a box plot draws.
Mean or Median? A Decision Table
| Situation | Report | Reason |
|---|---|---|
| Symmetric, roughly normal, no outliers | Mean with standard deviation | Uses every observation, matches sampling theory |
| Skewed data: income, rent, waiting times | Median with IQR | Typical value without tail distortion |
| Ordinal scales: ratings, ranks, Likert items | Median or mode | Equal intervals between levels are not guaranteed |
| You need totals to reconcile | Mean | Only mean times n reproduces the sum |
| Heavy contamination or data entry risk | Median or trimmed mean | High breakdown point |
| Multimodal distribution | Median plus a histogram | Any single centre hides the structure |
The reconciliation rule is the one practitioners forget: the mean is the only centre with the additive property , so budgets, totals and per-capita arithmetic must use it even when the distribution is skewed — in that case report both, or report the median with the total stated separately.
The Median in Machine Learning
In ML, the median is the robust choice:
| ML Application | Why Median? | What Happens with Mean |
|---|---|---|
| MAE / Huber Loss | Minimizes to median | MSE is pulled by outliers |
| RobustScaler | Centers at median, scales by IQR | StandardScaler affected by outliers |
| Missing value imputation | Robust to extreme values | Mean imputation distorted by outliers |
| Outlier detection | IQR fence uses quartiles | Mean ± std fails on skewed data |
| Feature ranking | Median test for non-normal data | t-test assumes normality |
import numpy as np
from sklearn.linear_model import HuberRegressor, LinearRegression
from sklearn.preprocessing import RobustScaler, StandardScaler
np.random.seed(42)
# Compare MSE vs MAE on data with outliers
n = 200
X = np.random.randn(n, 1) * 10
y = 3 * X[:,0] + np.random.randn(n) * 5
# Add outliers
y[::20] += np.random.randn(10) * 50 # every 20th point is extreme
# MSE model (minimizes to mean) — affected by outliers
mse_model = LinearRegression().fit(X, y)
print(f"MSE model (uses mean): coef = {mse_model.coef_[0]:.3f}")
# MAE model (minimizes to median) — robust
mae_model = HuberRegressor(epsilon=1.35).fit(X, y)
print(f"MAE model (uses median): coef = {mae_model.coef_[0]:.3f}")
print(f"True coefficient: 3.0\n")
# RobustScaler vs StandardScaler
data = np.concatenate([np.random.normal(50, 10, 100), [500, -200]]) # with outliers
robust = RobustScaler() # uses median and IQR
standard = StandardScaler() # uses mean and std
print(f"Data with outliers: mean={np.mean(data):.1f}, median={np.median(data):.1f}")
print(f"StandardScaler center: {standard.fit_transform(data.reshape(-1,1)).mean():.1f}")
print(f"RobustScaler center: {robust.fit_transform(data.reshape(-1,1)).mean():.1f}")
💡Quantile regression generalizes the idea
Frequently Asked Questions
Can the median be a value that is not in the dataset?
Yes. With an even sample size it is the average of the two middle observations, and for grouped or interpolated data it is an estimate inside a class. Only for odd on raw data is the median guaranteed to be an observed value.
Does the median care how extreme an outlier is?
No. It cares only about rank. Replacing the maximum with a value a thousand times larger leaves the median bit-for-bit identical, which is why the median is the default headline for income and property prices.
Why does absolute error loss produce the median?
Differentiating gives (points below) minus (points above); the sum is flat exactly where those counts balance. Median regression therefore fits the middle of the response distribution rather than its mean.
Is the median a good summary for multimodal data?
It is safe but uninformative — a single middle value can fall in the trough between two modes where almost no observations live. Plot the distribution and report the modes alongside any centre.
Common Mistakes
Using the mean for heavily skewed data and calling it typical
Fix: Report the median with the IQR for income, prices and waiting times, and keep the mean only when totals must reconcile.
Computing the median of an unsorted list by index
Fix: Sort first, then read the middle position; for even n average the two central values.
Applying the mean formula to ordinal ratings
Fix: Ordinal levels have no guaranteed equal spacing, so use the median or the mode for Likert-style responses.
Key Takeaways
- The median splits the sorted data in half: the (n+1)/2 position for odd n, the average of the two central values for even n
- Its 50% breakdown point means more than half the sample must be contaminated before it fails, while the mean fails with a single point
- The median minimizes the sum of absolute deviations, which is why MAE loss and quantile regression at 0.5 converge on it
- Grouped data needs interpolation, and the answer depends on where the class boundary is declared to lie
- Pair the median with the IQR, and use the mean only when symmetry holds or when sums must reconcile
Interview Questions
Q1: Why is the median preferred for reporting household income?
Income is strongly right-skewed, so a few very high earners pull the mean above what a typical household experiences. The median ignores magnitude beyond rank and therefore describes the centre household accurately.
Q2: What is the breakdown point of the median, and why does it matter?
50%. Contamination has to exceed half the sample before the median can be moved arbitrarily far, whereas the mean has a breakdown point of zero and is ruined by one bad value.
Q3: How do you find the median of grouped data?
Identify the class where the cumulative frequency passes n/2, then interpolate inside it with L + ((n/2 − F)/f) × h, stating the boundary convention you used because it shifts the result.
Q4: Why does MAE regression estimate the median while MSE regression estimates the mean?
The sum of absolute deviations is minimized where the counts of points below and above balance — the median — while the sum of squared deviations is minimized where signed deviations cancel, which is the mean.