Statistical modeling with Python · Lesson 4 of 16
Confidence intervals in Python
Compute a 95% confidence interval for a mean with scipy.stats.t and for a proportion with statsmodels, and learn what the interval really says.
A sample gives you one average, but a different sample would give a slightly different one. A confidence interval puts a range around the estimate to show how much it could move: "the average wait is 5.26 minutes, 95% CI 4.68 to 5.84". It is the most useful single number to report next to any estimate.
A confidence interval for a mean
A café timed 15 customers' waits in minutes. Three ingredients make the interval: the sample mean, the standard error (how much the mean itself wobbles from sample to sample: sd / √n) and a multiplier from the t distribution, a slightly wider cousin of the normal used for small samples.
import numpy as np
from scipy import stats
waits = np.array([4.2, 6.1, 3.8, 5.5, 7.0, 4.9, 5.2, 6.8, 3.5, 5.9,
4.4, 6.3, 5.0, 4.7, 5.6])
n = len(waits)
mean = waits.mean()
se = stats.sem(waits) # standard error: sd / sqrt(n), sd with n - 1
print(f"n = {n}, mean = {mean:.2f}, standard error = {se:.3f}")
low, high = stats.t.interval(0.95, df=n - 1, loc=mean, scale=se)
print(f"95% CI: {low:.2f} to {high:.2f}")n = 15, mean = 5.26, standard error = 0.271 95% CI: 4.68 to 5.84
The same thing step by step, so nothing is magic: the t multiplier for 95% and 14 degrees of freedom (n − 1) is about 2.145; the interval is mean ± multiplier × standard error.
import numpy as np
from scipy import stats
waits = np.array([4.2, 6.1, 3.8, 5.5, 7.0, 4.9, 5.2, 6.8, 3.5, 5.9,
4.4, 6.3, 5.0, 4.7, 5.6])
n = len(waits)
mean = waits.mean()
se = waits.std(ddof=1) / np.sqrt(n)
t_mult = stats.t.ppf(0.975, df=n - 1)
print(f"t multiplier: {t_mult:.3f}")
print(f"95% CI: {mean - t_mult * se:.2f} to {mean + t_mult * se:.2f}")t multiplier: 2.145 95% CI: 4.68 to 5.84
How to read a confidence interval
- What it means: the method catches the true average in 95% of samples. Informally: values inside the interval are plausible for the true mean, values far outside are not.
- What it does not mean: it is not where 95% of the customers' waits fall. Single waits vary far more (from 3.5 to 7.0 here). The interval is about the average.
- Width: more data gives a narrower interval (the standard error shrinks with √n). Asking for more confidence (99%) gives a wider one.
import numpy as np
from scipy import stats
waits = np.array([4.2, 6.1, 3.8, 5.5, 7.0, 4.9, 5.2, 6.8, 3.5, 5.9,
4.4, 6.3, 5.0, 4.7, 5.6])
mean, se, df = waits.mean(), stats.sem(waits), len(waits) - 1
for level in [0.90, 0.95, 0.99]:
low, high = stats.t.interval(level, df=df, loc=mean, scale=se)
print(f"{level:.0%}: {low:.2f} to {high:.2f} (width {high - low:.2f})")90%: 4.78 to 5.74 (width 0.95) 95%: 4.68 to 5.84 (width 1.16) 99%: 4.45 to 6.07 (width 1.61)
A confidence interval for a proportion
For a share ("38 of 120 visitors signed up"), use proportion_confint from statsmodels. The Wilson method works well even for small samples or shares near 0% or 100%; the simple "normal" method can give silly intervals there.
from statsmodels.stats.proportion import proportion_confint
signed, visitors = 38, 120
low, high = proportion_confint(signed, visitors, alpha=0.05, method="wilson")
print(f"share: {signed / visitors:.1%}")
print(f"95% CI: {low:.1%} to {high:.1%}")share: 31.7% 95% CI: 24.0% to 40.4%
alpha=0.05 means 95% confidence (1 − alpha).
model.conf_int(). You will read those in Linear regression in Python with statsmodels; they mean exactly the same thing as here.✎ Exercise
Twelve phone batteries lasted these numbers of hours. Print the mean with 2 decimals and the 95% confidence interval for the mean (2 decimals).
Hint: stats.t.interval(0.95, df=len(hours) - 1, loc=mean, scale=stats.sem(hours)).
import numpy as np
from scipy import stats
hours = np.array([10.2, 11.5, 9.8, 10.9, 12.1, 10.4, 11.0, 9.5, 10.8, 11.7, 10.1, 11.2])
# your code here
Expected output:
mean: 10.77 95% CI: 10.26 to 11.27
Show a solution
import numpy as np
from scipy import stats
hours = np.array([10.2, 11.5, 9.8, 10.9, 12.1, 10.4, 11.0, 9.5, 10.8, 11.7, 10.1, 11.2])
mean = hours.mean()
low, high = stats.t.interval(0.95, df=len(hours) - 1, loc=mean, scale=stats.sem(hours))
print(f"mean: {mean:.2f}")
print(f"95% CI: {low:.2f} to {high:.2f}")mean: 10.77 95% CI: 10.26 to 11.27
Check yourself
1. A 95% CI for the mean wait is 4.68 to 5.84 minutes. Which statement is right?
The interval is about the average, not single customers, and it comes from a method that catches the truth in 95% of samples.
2. What happens to the interval if you collect four times as much data?
The standard error shrinks with √n, and √4 = 2.
3. Which interval is wider for the same data?
More confidence needs a wider net.