Data analysis · Intermediate · 16 min
Calculate and explain confidence intervals the right way
By Padding · Updated 18 Nov 2026
Python 3.15 · SciPy 1.18.1 · statsmodels 0.15.0 · NumPy 2.5.5 · pandas 3.1.1 · uv 0.13 (checked on python:3.15-slim)
You will compute a t interval for a mean, a Wilson interval for a proportion and a bootstrap interval for a median in Python, prove by simulation that about 95 in 100 intervals catch the true value, and write the results up in sentences that say what a confidence interval does and does not mean.
On this page
A single number from a sample is a guess. "The home screen loads in 4.12 seconds on average" sounds precise, but it came from 40 sessions, and another 40 would give a different mean. A confidence interval says how far off that guess could reasonably be. It is the honest way to report a sample, and also one of the most misexplained ideas in analysis.
This tutorial covers three intervals you will use most, each matched to the kind of number it describes:
- a t interval for a mean (load times),
- a Wilson interval for a proportion (failed checkouts), and why the textbook normal interval breaks near 0% and 100%,
- a bootstrap interval for a median (delivery times), where no simple formula exists.
Then you check by simulation that the method really catches the true value about 95 times in 100, and write the results in sentences a colleague cannot misread.
The data is generated and invented: a pilot of a shopping app tested on low-end Android phones over 3G. Everything runs in a throwaway folder, ~/ci-demo, which you delete at the end.
Step 1 · Create the project and generate the pilot data
Make the folder and add NumPy, pandas, SciPy and statsmodels. Each range allows patch releases only, so a new minor version cannot change your numbers. On prepaid mobile data, note that the four packages download about 70 MB together.
mkdir -p ~/ci-demo
cd ~/ci-demo
uv init --no-package --python 3.15
uv add "numpy>=2.5,<2.6" "pandas>=3.1,<3.2" "scipy>=1.18,<1.19" "statsmodels>=0.15,<0.16"
uv run python -c "import numpy, pandas, scipy, statsmodels; print(numpy.__version__, pandas.__version__, scipy.__version__, statsmodels.__version__)"Now write make_data.py. A seeded generator means you get the same three files every time:
cat > make_data.py <<'PY'
import numpy as np
import pandas as pd
rng = np.random.default_rng(1815)
# 40 cold starts of the app's home screen on low-end Android phones over 3G, in seconds.
load = (rng.gamma(shape=6.0, scale=0.5, size=40) + 0.8).round(2)
pd.DataFrame({"session": range(1, 41), "load_s": load}).to_csv("load_times.csv", index=False)
# 60 checkout attempts in a pilot; 2 of them failed.
failed = np.zeros(60, dtype=bool)
failed[rng.choice(60, size=2, replace=False)] = True
pd.DataFrame({"attempt": range(1, 61), "failed": failed}).to_csv("checkouts.csv", index=False)
# 45 delivery times in minutes: most are quick, a few take hours.
minutes = rng.lognormal(mean=3.4, sigma=0.7, size=45).round()
pd.DataFrame({"order": range(1, 46), "minutes": minutes}).to_csv("deliveries.csv", index=False)
print("load_times.csv:", len(load), "rows")
print("checkouts.csv:", len(failed), "rows,", int(failed.sum()), "failed")
print("deliveries.csv:", len(minutes), "rows")
PY
uv run make_data.py
head -3 load_times.csvCheck it worked
The version line prints 2.5.5 3.1.1 1.18.1 0.15.0, or later patch releases. The script reports 40 load times, 60 checkouts with 2 failures and 45 deliveries, and head shows the first session at 1,4.32.
Step 2 · Build a t interval for the mean load time
The interval for a mean is the sample mean plus or minus a margin. The margin is the standard error (the standard deviation divided by the square root of n) times a critical value. With a small sample you do not know the population's spread, only the sample's, so the critical value comes from the t distribution with n − 1 degrees of freedom rather than the normal distribution's 1.96. The t value is a little larger, which widens the interval to pay for that extra uncertainty.
Write mean_ci.py. It works the interval out by hand, then asks SciPy for the same thing:
cd ~/ci-demo
cat > mean_ci.py <<'PY'
import numpy as np
import pandas as pd
from scipy import stats
x = pd.read_csv("load_times.csv")["load_s"].to_numpy()
n = len(x)
mean = x.mean()
sd = x.std(ddof=1) # sample standard deviation
se = sd / np.sqrt(n) # standard error of the mean
t_crit = stats.t.ppf(0.975, df=n - 1)
low, high = mean - t_crit * se, mean + t_crit * se
print(f"n {n} mean {mean:.2f} s sd {sd:.2f} se {se:.3f}")
print(f"t critical value (df {n - 1}): {t_crit:.3f}")
print(f"95% CI by hand: {low:.2f} to {high:.2f} s")
ci = stats.ttest_1samp(x, popmean=0).confidence_interval(confidence_level=0.95)
print(f"95% CI by SciPy: {ci.low:.2f} to {ci.high:.2f} s")
PY
uv run mean_ci.pyTwo details are easy to get wrong. ddof=1 divides by n − 1, which is the sample standard deviation; NumPy's default divides by n and gives a slightly narrow interval. And 0.975 in t.ppf is not a typo: a 95% interval leaves 2.5% in each tail, so you need the point with 97.5% below it.
The popmean=0 argument is there only because ttest_1samp needs one for its test. The confidence interval does not depend on it.
The t interval assumes the sample mean is roughly normally distributed. With 40 values from a mildly skewed distribution like this one, that holds well enough. With 10 values from a very skewed one, it does not, and the bootstrap later in this tutorial is a safer choice.
Check it worked
The script prints a mean of 4.12 s, a standard deviation of 1.71 and a standard error of 0.270, a critical value of 2.023 (larger than 1.96), and the same interval twice: 3.57 to 4.66 s.
Step 3 · Use a Wilson interval for a proportion
Two of 60 checkouts failed: 3.33%. The interval most textbooks teach for a proportion is the normal (or Wald) interval, p ± 1.96 × √(p(1 − p)/n). It works when n is large and p is near the middle. Near 0% or 100% it falls apart, and failure rates, conversion rates and error rates usually live there.
The Wilson interval solves the same problem a different way: instead of centring on the observed p, it asks which true rates would make the observed count unsurprising. It never goes below 0 or above 1, and it stays sensible with small counts. Write proportion_ci.py to compare them:
cd ~/ci-demo
cat > proportion_ci.py <<'PY'
import numpy as np
import pandas as pd
from statsmodels.stats.proportion import proportion_confint
df = pd.read_csv("checkouts.csv")
k = int(df["failed"].sum())
n = len(df)
p = k / n
print(f"{k} failures in {n} attempts: {p:.2%}")
# The textbook normal (Wald) interval, worked by hand.
half = 1.96 * np.sqrt(p * (1 - p) / n)
print(f"normal by hand: {p - half:.2%} to {p + half:.2%}")
for method in ("normal", "wilson"):
low, high = proportion_confint(k, n, alpha=0.05, method=method)
print(f"{method + ' (statsmodels)':<20}: {low:.2%} to {high:.2%}")
print("if no checkout had failed:")
for method in ("normal", "wilson"):
low, high = proportion_confint(0, n, alpha=0.05, method=method)
print(f" {method:<6}: {low:.2%} to {high:.2%}")
PY
uv run proportion_ci.pyRead the output line by line:
- The normal interval worked by hand starts at −1.21%. A failure rate cannot be negative, so the formula is already telling you it does not fit.
- statsmodels clips that lower end to 0.00%. The output looks tidy, but the interval is still the broken one: too narrow, and centred in the wrong place.
- The Wilson interval runs from 0.92% to 11.36%. It is not symmetric around 3.33%, because with only two failures the true rate could plausibly be quite a bit higher, but not much lower.
- With zero failures, the normal interval collapses to 0.00% to 0.00%, which claims you know the failure rate exactly. Wilson says it could still be up to about 6%. Sixty clean checkouts is good news, not proof of perfection.
Use Wilson as your default for any proportion. In statsmodels it is method="wilson"; you rarely need the normal one at all.
Check it worked
The output shows a negative lower end (-1.21%) for the hand-worked normal interval, 0.92% to 11.36% for Wilson, and, with zero failures, 0.00% to 0.00% for normal against 0.00% to 6.02% for Wilson.
Step 4 · Bootstrap an interval for the median delivery time
Delivery times are skewed: most orders arrive within half an hour, a few take well over an hour. The median is the better summary here, but there is no simple textbook formula for its interval. The bootstrap builds one from the data itself:
- Draw 45 orders from your 45, with replacement, so some repeat and some are left out.
- Take the median of that resample.
- Repeat thousands of times. The spread of those medians shows how much the median wobbles from sample to sample.
- The percentile interval is the middle 95% of them: the 2.5th to the 97.5th percentile.
scipy.stats.bootstrap does all four steps. Write median_ci.py:
cd ~/ci-demo
cat > median_ci.py <<'PY'
import numpy as np
import pandas as pd
from scipy import stats
minutes = pd.read_csv("deliveries.csv")["minutes"].to_numpy()
print(f"n {len(minutes)} median {np.median(minutes):.0f} min mean {minutes.mean():.1f} min")
res = stats.bootstrap(
(minutes,),
np.median,
confidence_level=0.95,
n_resamples=9999,
method="percentile",
rng=np.random.default_rng(7),
)
ci = res.confidence_interval
print(f"95% bootstrap CI for the median: {ci.low:.0f} to {ci.high:.0f} min")
print(f"bootstrap standard error: {res.standard_error:.1f} min")
PY
uv run median_ci.pyThe data goes in as a tuple, (minutes,), because bootstrap also handles statistics that take several samples. The rng argument seeds the resampling: without it, the interval shifts slightly on every run, which is correct behaviour but confusing in a report.
The interval runs from 21 to 36 minutes around a median of 25, so it is lopsided: the slow deliveries in the tail make a higher median more plausible than a lower one. A formula that forced the interval to be symmetric would hide that.
SciPy's default method is "BCa", which adjusts the percentiles for bias and skew and usually covers the true value more reliably. The percentile method is used here because it is the easiest to explain. Try method="BCa" and compare; if the two disagree a lot, your sample is probably too small to say much about the median.
Check it worked
The script prints a median of 25 minutes with a mean of 31.9 (the tail pulls the mean up), an interval of 21 to 36 min and a bootstrap standard error of 3.6 minutes. Change the seed in default_rng(7) and run it again: the ends may move by a minute, not by ten.
Step 5 · Check coverage by simulation
"95% confidence" is a promise about the method, not about any one interval. If you took many samples and built an interval from each, about 95% of those intervals would contain the true value. With real data you never know the true value, so you cannot check it. With simulated data you can.
coverage.py does two checks. First, it draws 100 samples of 40 load times from a population whose true mean is 3.8 seconds and counts how many t intervals contain 3.8. Then it simulates 10,000 pilots of 60 checkouts with a true failure rate of 3% and counts how often the normal and Wilson intervals contain 3%:
cd ~/ci-demo
cat > coverage.py <<'PY'
import numpy as np
from scipy import stats
from statsmodels.stats.proportion import proportion_confint
rng = np.random.default_rng(42)
# Part 1: 100 samples of 40 from a population whose mean you know.
shape, scale, shift = 6.0, 0.5, 0.8
true_mean = shape * scale + shift
hits = 0
for _ in range(100):
sample = rng.gamma(shape, scale, size=40) + shift
ci = stats.ttest_1samp(sample, popmean=0).confidence_interval(0.95)
hits += ci.low <= true_mean <= ci.high
print(f"true mean {true_mean:.1f} s: {hits} of 100 t intervals contain it")
# Part 2: 10,000 pilots of 60 checkouts with a true failure rate of 3%.
true_p, n, sims = 0.03, 60, 10_000
k = rng.binomial(n, true_p, size=sims)
for method in ("normal", "wilson"):
low, high = proportion_confint(k, n, alpha=0.05, method=method)
cover = np.mean((low <= true_p) & (true_p <= high))
print(f"{method:<6} interval contains 3%: {cover:.1%} of {sims:,} pilots")
PY
uv run coverage.py96 of 100 is "about 95". Change the seed and you will see counts like 93 or 97: with only 100 intervals, the count itself varies. That is the point. Each of those 100 intervals either contains 3.8 or it does not; the 95% describes how often the procedure succeeds across many samples.
The second part shows why the previous step mattered. At a 3% failure rate with 60 attempts, the normal interval misses the true rate in about one pilot in six, far worse than the one in twenty it claims. Wilson's 96.7% is close to what it promises (slightly above here; because counts are whole numbers, the actual coverage swings a little above or below 95% depending on the true rate).
Check it worked
The script prints 96 of 100 t intervals contain it, then 83.9% for the normal interval and 96.7% for Wilson. If your normal figure is well below 95% and your Wilson figure is close to it, the simulation shows what it should.
Step 6 · Write the result in sentences that cannot be misread
The most common mistake is not in the code. It is the sentence "there is a 95% chance the true mean is between 3.57 and 4.66 seconds". Once you have computed this interval, the true mean is a fixed number: it is either inside or outside, and you do not know which. The 95% belongs to the method, as the simulation showed.
Wording that is correct and still useful:
- "The mean load time was 4.12 s (95% CI 3.57 to 4.66 s)." Give the estimate, the interval and the method, and let the reader see the precision.
- "Values between 3.57 and 4.66 s are consistent with this sample." This is a fair plain-language reading.
- "This interval came from a method that captures the true value about 95 times in 100." This is the definition, if someone asks.
Avoid "95% chance", "95% probability" and "we are 95% sure" about a single interval. If your audience reads English as a second language, or you translate the report, check the translated phrase too: "probability" and "confidence" often become the same word.
Write report.py, which recomputes all three intervals and saves them to report.md:
cd ~/ci-demo
cat > report.py <<'PY'
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.stats.proportion import proportion_confint
load = pd.read_csv("load_times.csv")["load_s"].to_numpy()
t_ci = stats.ttest_1samp(load, popmean=0).confidence_interval(0.95)
checkouts = pd.read_csv("checkouts.csv")
k, n = int(checkouts["failed"].sum()), len(checkouts)
w_low, w_high = proportion_confint(k, n, alpha=0.05, method="wilson")
minutes = pd.read_csv("deliveries.csv")["minutes"].to_numpy()
boot = stats.bootstrap((minutes,), np.median, n_resamples=9999,
method="percentile", rng=np.random.default_rng(7))
b = boot.confidence_interval
lines = [
"# Pilot results with 95% confidence intervals",
"",
f"- Home screen load time: mean {load.mean():.2f} s over {len(load)} sessions"
f" (95% CI {t_ci.low:.2f} to {t_ci.high:.2f} s, t interval).",
f"- Checkout failures: {k} of {n} ({k / n:.1%}; 95% CI {w_low:.1%} to {w_high:.1%},"
" Wilson interval).",
f"- Delivery time: median {np.median(minutes):.0f} min over {len(minutes)} orders"
f" (95% CI {b.low:.0f} to {b.high:.0f} min, percentile bootstrap, 9,999 resamples).",
"",
"A 95% confidence interval comes from a method that, used on many samples,"
" captures the true value about 95 times in 100. Any one interval either"
" contains the true value or it does not; the range shows how precisely"
" this sample pins it down.",
]
text = "\n".join(lines) + "\n"
with open("report.md", "w", encoding="utf-8") as f:
f.write(text)
print(text, end="")
PY
uv run report.py
grep -qi "chance\|probability" report.md && echo "reword the report" || echo "wording ok"The last line is a small guard: it searches the report for "chance" or "probability" and tells you to reword if either appears. Keep a check like this next to any script that writes interval text for other people.
When you have finished, delete the practice folder with rm -r ~/ci-demo. Check the path first: it removes everything inside it.
Check it worked
report.md lists the load time as 4.12 s with 95% CI 3.57 to 4.66 s, checkout failures as 2 of 60 (3.3%; 95% CI 0.9% to 11.4%, and the median delivery as 25 min with 95% CI 21 to 36 min, followed by the paragraph on what 95% means. The guard prints wording ok.
Next steps
- Put margins of error on survey percentages in read survey results without fooling yourself; for percentages near 0% or 100%, or small groups, swap its normal formula for the Wilson interval from this tutorial.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials