Pulse Data Hub

Bootstrap Confidence Intervals in Python, Tested

Bootstrap confidence intervals in Python let you put error bars on almost any statistic, including medians, with a few lines of NumPy. This guide builds one by hand, compares it with the textbook t interval on real restaurant tips, and then tests how often the bootstrap is actually right.

The idea behind the bootstrap

A confidence interval says how much a statistic would wobble if you could repeat the study. You cannot repeat it, so the bootstrap pretends the sample is the population: draw many new samples of the same size from your data, with replacement, compute the statistic each time, and read the interval from the spread. No normality assumption is needed.

Step 1: the data

The seaborn tips file has 244 restaurant bills. We study the tip as a percentage of the bill.

import numpy as np, pandas as pd
from scipy import stats
tips = pd.read_csv("tips.csv")
tips["pct"] = tips.tip / tips.total_bill * 100
x = tips.pct.values
print(len(x), x.mean(), np.median(x), x.std(ddof=1), stats.skew(x))

The mean tip is 16.08%, the median 15.48%, the standard deviation 6.11 points, and the skew is 3.33, a long right tail from a few very large tips (the maximum is 71.0%). The mean and median differ because of that tail, so a skewed shape is exactly where the textbook assumptions are shakier.

Step 2: the bootstrap by hand

rng = np.random.default_rng(0)
boot = np.array([rng.choice(x, len(x)).mean() for _ in range(10000)])
print(np.percentile(boot, [2.5, 97.5]), boot.std())

The 95% percentile interval for the mean is 15.35% to 16.88%, with a bootstrap standard error of 0.389. The classical t interval is 15.31% to 16.85%, nearly identical, which is expected with 244 observations.

Step 3: intervals for a statistic with no simple formula

The median has no one-line formula. The bootstrap handles it the same way: replace .mean() with np.median. The 95% interval for the median tip is 14.96% to 16.17%. SciPy also ships scipy.stats.bootstrap, which offers the bias-corrected BCa method; for the mean it gives 15.43% to 16.97%, shifted slightly right because the data are skewed.

res = stats.bootstrap((x,), np.mean, n_resamples=9999, method="BCa", random_state=0)
print(res.confidence_interval)

Step 4: comparing two groups

Do smokers tip a different percentage than non-smokers? Resample each group separately and take the difference of means.

a = tips[tips.smoker == "Yes"].pct.values   # 93 bills
b = tips[tips.smoker == "No"].pct.values    # 151 bills
d = [rng.choice(a, len(a)).mean() - rng.choice(b, len(b)).mean() for _ in range(10000)]
print(a.mean() - b.mean(), np.percentile(d, [2.5, 97.5]))

Smokers tipped 16.32% on average and non-smokers 15.93%, a gap of 0.39 points. The interval runs from −1.35 to 2.36, which includes zero, so the data do not show a difference. The same recipe gives an interval for the correlation between bill and tip (0.676, interval 0.569 to 0.761, from 2,000 resamples of whole rows). For significance tests on group differences see t-test vs Mann-Whitney in Python.

How often is the bootstrap right?

A method is only worth trusting if it covers the truth about 95% of the time. We checked on a skewed population (lognormal with sigma 0.5, true mean 1.133). For each sample size, 2,000 samples were drawn, and both a t interval and a 500-resample percentile bootstrap interval were built for each.

Bar chart: coverage of 95% intervals; bootstrap covers 87.6% at n=10, 92.1% at n=30 and 94.1% at n=100, slightly below the t interval each time
Coverage of nominal 95% intervals. Simulation with a fixed seed.

With 10 observations the bootstrap interval contained the true mean only 87.6% of the time, against 92.9% for the t interval. At 30 observations the figures were 92.1% and 93.6%, and at 100 they were 94.1% and 94.5%. The usual explanation (not tested here) is that a small sample rarely contains the extreme values the population has, so resampling from it understates the spread.

When the bootstrap fails

Statistics that depend on the extremes break it. The largest tip in the data is 71.0%. In 10,000 resamples, the maximum equalled that same value 62.8% of the time, so the bootstrap distribution of the maximum is a lumpy spike, not a usable interval.

  • Use it for means, medians, proportions, correlations and model metrics.
  • Avoid it for maxima, minima and very small samples (under about 30).
  • Resample whole rows when statistics involve two columns, and resample groups when rows are not independent.
  • Use 5,000 to 10,000 resamples for reporting, and fix the random seed.

Docs: scipy.stats.bootstrap. Related reading: exploratory data analysis in Python, statistical power and sample size and A/B test significance.

FAQ

How many bootstrap resamples do I need?

10,000 is a common choice. The interval endpoints barely change beyond a few thousand, but they do move with the random seed, so fix it.

Is the bootstrap better than the t interval?

Not here. With skewed data and small samples the t interval covered more often. The bootstrap earns its place for statistics such as the median, where no simple formula exists.

Which versions were used?

NumPy 2.5.3, SciPy 1.18.1 and pandas 3.0.5. The coverage simulation is one run with a fixed seed, so its percentages carry a sampling error of roughly half a point.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights