Resampling the data you already have
Many quantities you want to report have no textbook standard error. What is the confidence interval for a median, a ratio of two means, an AUC, a ninety-fifth percentile of latency, or the coefficient from a model that took an hour to fit? The delta method can sometimes manufacture one, but the algebra is punishing and the approximations fragile. The bootstrap replaces all of that with a single idea: your sample is itself a draw from the population, so treat the empirical distribution of the sample as a stand-in for the population and sample from it repeatedly.
What you get back is an approximation of the sampling distribution of your statistic, built from data rather than theory. From that approximation you can read a standard error, a confidence interval, a bias estimate, or a hypothesis test, and none of it requires knowing the shape of the underlying population. The method was popularised in the 1970s and 1980s precisely because computers made ten thousand resamples cheap while the analytical alternatives stayed hard.
The algorithm and why it works
The procedure is short enough to hold in your head. Draw a resample of the same size as the original data, with replacement, so that some observations appear twice and others not at all. Compute the statistic on that resample. Repeat ten thousand times. Sort the ten thousand values, and you now have an empirical sampling distribution whose quantiles are confidence limits and whose standard deviation is a standard error.
The justification rests on a substitution. The unknown population distribution is replaced by the empirical distribution that puts equal weight on each observed value, and the claim is that this substitute is close enough for the statistic's behaviour to transfer. It works remarkably well for statistics that are smooth functions of the data â means, medians, quantiles, regression coefficients â and it degrades for statistics at the boundary of their range, such as a maximum, or for very small samples where the empirical distribution is a poor reflection of the true one.
| Interval method | Construction | Best when | Cost |
|---|---|---|---|
| Percentile | Direct quantiles of the bootstrap distribution | Statistic is roughly symmetric | Cheap and simple |
| Basic (pivotal) | Reflect the percentile limits around the point estimate | Distribution is symmetric but shifted | Cheap |
| BCa | Adjusts for bias and skewness with acceleration terms | Statistic is biased or asymmetric | Needs jackknife |
| Studentized | Re-bootstraps to estimate a standard error per replicate | Highest accuracy required | Expensive |
Interval flavours: percentile, basic, BCa
The percentile interval is the most direct: take the lower and upper two-and-a-half percentiles of the bootstrap distribution and call them the limits. It has an appealing literal reading and works well when the bootstrap distribution is roughly symmetric around the estimate. Its weakness is that it silently assumes the distribution's centre matches the point estimate, which fails whenever the statistic is biased.
The basic interval corrects that by reflecting: instead of reading the quantiles directly, it takes twice the estimate minus the upper quantile for the lower limit, and twice the estimate minus the lower quantile for the upper. The BCa method goes further, adjusting for both bias â a mismatch between the bootstrap centre and the original estimate â and acceleration, which captures how the statistic's standard error changes with the data. BCa is the recommended default when accuracy matters, because it keeps coverage close to nominal across a much wider range of statistics, and the price is a jackknife computation that is trivial next to the bootstrap loop itself.
Permutation tests as the testing cousin
Where the bootstrap approximates a sampling distribution under the observed data, a permutation test approximates a null distribution under the assumption that labels are interchangeable. Compute your statistic on the real data, then shuffle the labels many times, recompute, and count how often the shuffled value is at least as extreme as the observed one. The resulting p-value is exact for the sharp null, because it comes from the actual reference distribution rather than an asymptotic approximation.
The two methods are complementary rather than competing. Bootstrap when you want an interval or a standard error for a quantity; permute when you want a p-value for a comparison. Both share the same implementation skeleton â a loop that resamples and recomputes â so once one is written, the other is a small variation. Both also inherit the same assumption about independence: resampling rows does nothing to repair data whose rows are clustered or serially correlated, and in those settings the resampling unit must be the cluster or the block rather than the individual observation.
When to bootstrap and when not to
Reach for the bootstrap when the statistic has no closed-form variance, when the distribution is visibly skewed with a sample large enough for the empirical distribution to be representative, or when you simply want an assumption-light cross-check on a parametric interval. For a mean with clean normal data and a decent sample, the t interval is exact and cheaper, and there is no reason to resample.
Two caveats deserve attention. Small samples below roughly twenty observations give the empirical distribution too little support, and the resulting intervals undercover; the BCa correction helps but does not fully repair the situation, and a parametric assumption or a subject-matter-informed prior may be the better path. And clustered or time-ordered data must be resampled at the level at which independence actually holds â a moving-block bootstrap for time series, a cluster bootstrap for grouped observations â otherwise the resampled datasets are artificially tidy and the intervals come out too narrow.
Bootstrap machinery in Python
import numpy as np
def bootstrap(data, stat_fn, n_boot=10_000, seed=0):
rng = np.random.default_rng(seed)
x = np.asarray(data, dtype=float)
n = x.size
estimates = np.array([stat_fn(rng.choice(x, n, replace=True))
for _ in range(n_boot)])
return estimates
def percentile_ci(estimates, confidence=0.95):
alpha = (1 - confidence) / 2 * 100
return (np.percentile(estimates, alpha),
np.percentile(estimates, 100 - alpha))
def basic_ci(original, estimates, confidence=0.95):
alpha = (1 - confidence) / 2 * 100
lo, hi = np.percentile(estimates, [alpha, 100 - alpha])
return 2 * original - hi, 2 * original - lo
latency = np.array([19, 21, 23, 20, 44, 22, 21, 25, 38, 20,
22, 24, 19, 71, 23, 21, 26, 22, 20, 24])
for name, fn in (("mean", np.mean), ("median", np.median),
("p90", lambda v: np.percentile(v, 90))):
est = bootstrap(latency, fn)
orig = fn(latency)
p_lo, p_hi = percentile_ci(est)
b_lo, b_hi = basic_ci(orig, est)
print(f"{name:7s} point={orig:6.2f} percentile=[{p_lo:.2f}, {p_hi:.2f}]"
f" basic=[{b_lo:.2f}, {b_hi:.2f}] se={est.std(ddof=1):.3f}")
Running the same resampling machinery over three statistics shows why one formula cannot serve all of them: the mean's interval is symmetric, the median's is tighter and slightly shifted, and the ninetieth percentile's is wide and visibly asymmetric. All three came from identical code with only the statistic swapped.
The second block implements a permutation test and a cluster-aware bootstrap, the two corrections most analyses forget.
import numpy as np
def permutation_pvalue(a, b, n_perm=20_000, seed=0):
rng = np.random.default_rng(seed)
pooled = np.concatenate([a, b])
n_a, observed = len(a), np.mean(a) - np.mean(b)
hits = 0
for _ in range(n_perm):
rng.shuffle(pooled)
if abs(np.mean(pooled[:n_a]) - np.mean(pooled[n_a:])) >= abs(observed):
hits += 1
return observed, (hits + 1) / (n_perm + 1)
def cluster_bootstrap(clusters, stat_fn=np.mean, n_boot=10_000, seed=0):
"""Resample whole clusters, then pool their observations."""
rng = np.random.default_rng(seed)
k = len(clusters)
estimates = []
for _ in range(n_boot):
picks = rng.integers(0, k, size=k)
pooled = np.concatenate([clusters[i] for i in picks])
estimates.append(stat_fn(pooled))
return np.array(estimates)
site_a = np.random.default_rng(3)
a = site_a.normal(12, 3, 40)
b = np.random.default_rng(4).normal(15, 3, 42)
print("permutation:", np.round(permutation_pvalue(a, b), 4))
clusters = [np.random.default_rng(100 + i).normal(50 + i, 4, 12)
for i in range(15)]
cb = cluster_bootstrap(clusters)
print("cluster bootstrap mean CI:",
np.round(np.percentile(cb, [2.5, 97.5]), 2))
The permutation call returns both the observed difference and a p-value that required no distributional assumption at all. The cluster version resamples whole groups, which keeps the within-cluster correlation intact and produces an interval noticeably wider than a naive row-level bootstrap would.
Resampling mistakes
Common Mistakes
Bootstrapping rows of clustered or time-ordered data
Fix: Resample clusters or moving blocks so the dependence structure survives inside each replicate.
Using a percentile interval on a clearly biased statistic
Fix: Move to BCa, which corrects for bias and skewness, or report the bootstrap bias explicitly.
Running only a few hundred resamples
Fix: Use at least ten thousand; the quantile estimates need that many draws to stabilise.
Expecting the bootstrap to rescue a sample of five observations
Fix: Small samples give the empirical distribution too little support; use a parametric assumption instead.
Forgetting to fix the random seed
Fix: Seed every resampling loop so published intervals can be reproduced exactly.
Reading a bootstrap interval as exact coverage
Fix: It is an approximation whose accuracy depends on the statistic and the sample size; state the method used.
Bootstrapping essentials
Where to go next
- Bootstrap Methods covers the full theory and implementation options.
- Bootstrap Confidence Intervals compares percentile, BCa, and studentized coverage in simulations.
- Permutation Tests develops exact hypothesis testing by label shuffling.
- Nonparametric Methods places resampling alongside rank-based alternatives.