Population Mean Estimation
To estimate a population mean μ, we use the sample mean x̄ as the point estimate and build a confidence interval around it. Because the population standard deviation σ is almost never known, the interval uses the sample standard deviation s and the t-distribution:
x̄ ± t* × s / √n with df = n − 1Conditions
- Random sample of independent observations.
- Normality: the population is roughly normal, or the sample is large enough (n ≥ 30 is a common rule of thumb) for the Central Limit Theorem to make
x̄approximately normal. For small samples, check a histogram or Q–Q plot for strong skew and outliers.
Step by step
A coffee roaster weighs 15 randomly chosen "250 g" bags:
import math
import statistics
from scipy import stats
bags = [251.2, 248.9, 252.4, 250.1, 249.5, 253.0, 250.8, 247.6,
251.9, 250.4, 249.2, 252.7, 250.0, 248.4, 251.5]
n = len(bags)
xbar = statistics.mean(bags)
s = statistics.stdev(bags)
se = s / math.sqrt(n)
t_star = stats.t.ppf(0.975, df=n - 1)
margin = t_star * se
print(f"n = {n}, mean = {xbar:.3f} g, s = {s:.3f} g")
print(f"SE = {se:.4f}, t* (df={n - 1}) = {t_star:.3f}")
print(f"margin of error = {margin:.3f} g")
print(f"95% CI for μ: ({xbar - margin:.2f}, {xbar + margin:.2f}) g")n = 15, mean = 250.507 g, s = 1.620 g
SE = 0.4182, t* (df=14) = 2.145
margin of error = 0.897 g
95% CI for μ: (249.61, 251.40) g
We are 95% confident that the mean weight of all bags from this roaster is between about 249.6 g and 251.4 g. The interval contains 250 g, so these data give no indication that the bags are under- or over-filled on average.
The one-liner
SciPy can build the interval directly from the t-distribution, using stats.sem for the standard error:
import numpy as np
from scipy import stats
bags = np.array([251.2, 248.9, 252.4, 250.1, 249.5, 253.0, 250.8, 247.6,
251.9, 250.4, 249.2, 252.7, 250.0, 248.4, 251.5])
low, high = stats.t.interval(0.95, df=len(bags) - 1, loc=bags.mean(), scale=stats.sem(bags))
print(f"95% CI: ({low:.2f}, {high:.2f})")
low, high = stats.t.interval(0.99, df=len(bags) - 1, loc=bags.mean(), scale=stats.sem(bags))
print(f"99% CI: ({low:.2f}, {high:.2f})")95% CI: (249.61, 251.40)
99% CI: (249.26, 251.75)
Newer SciPy versions also offer stats.ttest_1samp(bags, 250).confidence_interval(), which you will use in Testing a Mean.
Known σ: the z-interval
In the rare case that σ is known from long experience (for example, a machine's precision is documented by the manufacturer), use z* instead:
x̄ ± z* × σ / √nimport math
from scipy import stats
xbar, sigma, n = 250.45, 1.6, 15 # sigma known from the filling machine's spec
z_star = stats.norm.ppf(0.975)
margin = z_star * sigma / math.sqrt(n)
print(f"95% z-interval: ({xbar - margin:.2f}, {xbar + margin:.2f})")95% z-interval: (249.64, 251.26)
Intervals for several groups
With pandas you can compute an interval for every group at once. Here are simulated fuel consumptions (litres per 100 km) for three car models:
import numpy as np
import pandas as pd
from scipy import stats
rng = np.random.default_rng(77)
cars = pd.DataFrame({
"model": np.repeat(["Atlas", "Breeze", "Comet"], [12, 20, 35]),
"l_per_100km": np.concatenate([rng.normal(7.8, 0.6, 12),
rng.normal(6.4, 0.5, 20),
rng.normal(6.9, 0.7, 35)]),
})
def ci95(x):
low, high = stats.t.interval(0.95, len(x) - 1, loc=x.mean(), scale=stats.sem(x))
return pd.Series({"n": len(x), "mean": x.mean(), "low": low, "high": high})
print(cars.groupby("model")["l_per_100km"].apply(ci95).unstack().round(2)) n mean low high
model
Atlas 12.0 7.85 7.35 8.35
Breeze 20.0 6.27 6.03 6.51
Comet 35.0 6.95 6.70 7.19
The intervals for Atlas and Breeze don't overlap at all, a strong hint that their true mean consumptions differ. Comet's interval is the narrowest because it has the most cars measured. (To test differences between groups properly, see One-Way ANOVA.)
Sample size for a mean
To reach a margin of error E, you need about n = (z* × σ / E)², using a guess of σ from earlier data or a pilot study:
import math
from scipy import stats
sigma_guess = 1.6
for E in [1.0, 0.5, 0.25]:
n = math.ceil((stats.norm.ppf(0.975) * sigma_guess / E) ** 2)
print(f"to estimate the mean bag weight within ±{E} g: n = {n}")to estimate the mean bag weight within ±1.0 g: n = 10
to estimate the mean bag weight within ±0.5 g: n = 40
to estimate the mean bag weight within ±0.25 g: n = 158
Halving the margin of error needs four times as many bags.
Test yourself
A sample of n = 25 has x̄ = 80 and s = 10. What is the standard error of the mean?
- 10
- 2
- 0.4
- 3.2
Why is t* used instead of z* in most confidence intervals for a mean?
- t* is always smaller
- σ is unknown and estimated by s, adding uncertainty
- The sample is not random
- The mean is not normally distributed
A 95% CI for mean battery life is (9.2, 10.6) hours. The manufacturer claims 11 hours. What does the interval suggest?
- The claim is plausible
- The true mean is likely below the claimed 11 hours
- The true mean is exactly 9.9 hours
- Nothing, intervals can't be compared to claims