To get a bootstrap confidence interval in Python, pass your samples and a statistic function to scipy.stats.bootstrap. It resamples your data with replacement thousands of times, recomputes the statistic each time, and returns an interval from the spread of those results. It suits A/B test metrics that aren't normally distributed, like revenue per user, and statistics with no simple formula, like a median. The code below targets SciPy 1.18.
Quick Example
This builds a skewed revenue-per-user dataset (300 users per group, lognormal) and bootstraps the difference in mean revenue:
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
rng = np.random.default_rng(17)
control = rng.lognormal(mean=3.0, sigma=1.3, size=300)
treatment = rng.lognormal(mean=3.25, sigma=1.3, size=300)
def mean_diff(t, c, axis=-1):
return np.mean(t, axis=axis) - np.mean(c, axis=axis)
res = stats.bootstrap((treatment, control), mean_diff, n_resamples=9999,
confidence_level=0.95, method="BCa", rng=17)
low, high = res.confidence_interval
observed = mean_diff(treatment, control)
print(f"observed lift ${observed:.2f}, 95% CI [{low:.2f}, {high:.2f}]")
fig, ax = plt.subplots(figsize=(7.5, 4.5))
ax.hist(res.bootstrap_distribution, bins=60, color="#14b8a6", edgecolor="white")
ax.axvline(low, color="#be123c", lw=2, ls="--")
ax.axvline(high, color="#be123c", lw=2, ls="--", label=f"95% CI: [{low:.1f}, {high:.1f}]")
ax.axvline(0, color="#0f172a", lw=1.5, label="No difference")
ax.axvline(observed, color="#f59e0b", lw=2, label="Observed difference")
ax.set(xlabel="Difference in mean revenue per user ($), treatment minus control",
ylabel="Bootstrap resamples", title="Bootstrap distribution of the lift (9,999 resamples)")
ax.legend()

The observed lift is $18.61 per user, and the 95% BCa interval is roughly $4 to $46. Zero sits outside it, so the lift is distinguishable from no change. The histogram has a longer right tail, which is what a skewed metric produces and why the interval is lopsided around the estimate.
The statistic receives the two samples and must accept an axis argument, because SciPy calls it on stacked resamples all at once. np.mean(..., axis=axis) does that. The rng keyword is the current way to seed (older SciPy versions used random_state, which still works but is being phased out). The default method is "BCa".
How Does the Bootstrap Work?
- Draw a sample of the same size from your data, with replacement, separately for each group.
- Compute the statistic on that resample (here, treatment mean minus control mean).
- Repeat several thousand times. The pile of results is the bootstrap distribution.
- Read the interval off that distribution.
It estimates how much your statistic would vary if you could rerun the experiment, using your own data as the stand-in for the population. No assumption of normality is needed, which is the draw for revenue, session length, and other heavy-tailed metrics.
Bootstrap Without scipy: a NumPy Loop
The same thing in plain NumPy takes a few lines, which helps when you need a custom resampling scheme:
B = 5000
boot = np.empty(B)
rng2 = np.random.default_rng(3)
for i in range(B):
t = rng2.choice(treatment, size=len(treatment), replace=True)
c = rng2.choice(control, size=len(control), replace=True)
boot[i] = t.mean() - c.mean()
print(np.percentile(boot, [2.5, 97.5]).round(2))
This percentile interval comes out at about $1.35 to $39.88. It differs a little from the SciPy numbers because it is a different method and a different random stream.
Percentile vs BCa vs Normal Intervals
scipy.stats.bootstrap takes method="percentile", "basic", or "BCa". The percentile method simply takes the 2.5th and 97.5th percentiles of the bootstrap distribution. BCa (bias-corrected and accelerated) adjusts those cutoffs for bias and skew in the distribution, so it is the default and usually the better choice for skewed data. Here is the same experiment under each approach, plus a bootstrapped median:
def ci_for(stat, method):
r = stats.bootstrap((treatment, control), stat, n_resamples=9999,
method=method, rng=17)
return r.confidence_interval
def median_diff(t, c, axis=-1):
return np.median(t, axis=axis) - np.median(c, axis=axis)
diff = treatment.mean() - control.mean()
se = np.sqrt(treatment.var(ddof=1) / len(treatment) + control.var(ddof=1) / len(control))
normal = (diff - 1.96 * se, diff + 1.96 * se)
pct = ci_for(mean_diff, "percentile")
bca = ci_for(mean_diff, "BCa")
med = ci_for(median_diff, "BCa")
print(f"normal approximation: [{normal[0]:.2f}, {normal[1]:.2f}]")
print(f"percentile: [{pct.low:.2f}, {pct.high:.2f}]")
print(f"BCa: [{bca.low:.2f}, {bca.high:.2f}]")
print(f"median diff, BCa: [{med.low:.2f}, {med.high:.2f}]")

| Method | Interval for the mean difference |
|---|---|
| Normal approximation (estimate ± 1.96 SE) | -0.83 to 38.05 |
| Bootstrap, percentile | 1.05 to 40.01 |
| Bootstrap, BCa | 3.96 to 46.50 |
The three disagree on whether zero is in range. The normal approximation is symmetric, so it extends below the estimate as far as above it and just reaches zero. The bootstrap intervals shift to the right to follow the long right tail of the data. That is one dataset, not proof that BCa is always right. With 300 users per group and heavy skew, the plain interval is the one least likely to be reliable, but a result this close to zero should be treated as borderline whichever method you pick. More data, or CUPED, tightens all of them.
Bootstrap a Median or Any Other Statistic
The median has no neat standard-error formula, but the bootstrap handles it with no extra work: the median_diff function above is the only change. The BCa interval for the median difference is $4.00 to $14.55 (observed median difference $9.23). That is much narrower than the interval for the mean, because the median ignores the few very large orders that dominate the mean's variability. The two answer different questions: the mean tells you about total revenue, the median about the typical user. Pick the one that matches the decision. The same pattern works for a trimmed mean, a percentile such as p90, or a ratio of two metrics.
How Many Bootstrap Resamples Do I Need?
SciPy defaults to 9,999. Fewer resamples add Monte Carlo noise to the interval ends. Here is how much the upper end of the percentile interval moves across 8 different seeds:
for n_res in (200, 1000, 9999):
ends = [stats.bootstrap((treatment, control), mean_diff, n_resamples=n_res,
method="percentile", rng=s).confidence_interval.high
for s in range(8)]
print(n_res, round(np.std(ends), 3))
Which prints:
n_resamples |
Std dev of the upper end across seeds |
|---|---|
| 200 | $1.79 |
| 1,000 | $0.89 |
| 9,999 | $0.23 |
A few thousand resamples is plenty for a report. The noise from resampling is small next to the uncertainty from having only 300 users per group, which more resamples cannot fix.
When Does the Bootstrap Fail?
- Tiny samples. With a few dozen observations the resamples can't represent the tail, and the interval comes out too narrow.
- Extreme statistics. The maximum or a very high percentile of a small sample bootstraps badly.
- Non-independent data. If one user contributes many rows (sessions, orders), resample users, not rows, or the interval will be far too narrow. Pass one value per user, or resample whole clusters.
- Selection by peeking. Bootstrapping doesn't fix repeated looks at a running experiment. See the sample size post below for setting the duration in advance.
Which Interval Should I Use?
| Situation | Use |
|---|---|
| Large samples, roughly symmetric metric | Normal approximation or Welch's t-test; the bootstrap adds little |
| Skewed metric such as revenue, moderate sample | scipy.stats.bootstrap with method="BCa" |
| Median, percentile, ratio, or other custom statistic | scipy.stats.bootstrap with a custom function |
| Clustered or repeated measures | Bootstrap whole users or clusters |
| Many datasets to analyze, speed matters | Vectorized statistic (as above) with n_resamples near 2,000 |