ADescribe · bootstrap.ci
Bootstrap confidence interval
How precise is a mean, median, SD or trimmed mean — or a difference between two groups — without assuming normality?
Nonparametric bootstrap with BCa (default), percentile, basic and normal intervals for one sample or the difference between two groups (resampling within groups). Resamples come from a portable random stream, so Python and R draw the same bootstrap samples and agree exactly.
A real result
Example “Mean one sample”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
42.13, 95% BCa CI [36.78, 48.77]
- Mean of Ozone
- 42.129
- 95% BCa CI
- [36.779, 48.772]
- Bootstrap SE
- 3.005
Plots
View data
| Bootstrap mean |
|---|
| 37.888 |
| 49.319 |
| 44.819 |
| 41.224 |
| 46.629 |
| 46.862 |
| 39.362 |
| 38.362 |
| 39.293 |
| 46.086 |
| 38.440 |
| 47.345 |
| 35.655 |
| 41.276 |
| 42.379 |
| 35.664 |
| 42.534 |
| 43.440 |
| 38.293 |
| 43.043 |
| 41.129 |
| 41.517 |
| 37.422 |
| 46.414 |
| 38.302 |
| 41.793 |
| 43.095 |
| 39.319 |
| 39.078 |
| 43.112 |
| 35.155 |
| 41.578 |
| 39.931 |
| 40.250 |
| 41.664 |
| 41.328 |
| 42.819 |
| 39.966 |
| 39.155 |
| 41.905 |
| 43.862 |
| 39.612 |
| 41.069 |
| 41.328 |
| 38.112 |
| 43.233 |
| 39.759 |
| 42.922 |
| 41.216 |
| 43.948 |
| 41 |
| 39.078 |
| 41.336 |
| 40.328 |
| 41.974 |
| 40.224 |
| 38.414 |
| 41.362 |
| 43.948 |
| 43.164 |
First 60 of 1999 rows.
95% intervals
| Interval | Lower | Upper |
|---|---|---|
| BCa (bias-corrected and accelerated) | 36.779 | 48.772 |
| Percentile | 36.414 | 48.269 |
| Basic | 35.990 | 47.845 |
| Normal | 36.208 | 47.988 |
Bootstrap distribution
| Quantity | Value |
|---|---|
| Resamples (B) | 1,999 |
| SE | 3.005 |
| Bias | 0.0310 |
| Bias correction z₀ | 0.0245 |
| Acceleration a | 0.0190 |
- 37 of 153 rows were left out because a value was missing.
- Seed 42: the same resamples in Python and R (portable Wichmann–Hill stream).
- BCa corrects the percentile interval for bias and skewness (acceleration from the jackknife); prefer it unless n is very small.
42.13, 95% BCa CI [36.78, 48.77]
- Mean of Ozone
- 42.129
- 95% BCa CI
- [36.779, 48.772]
- Bootstrap SE
- 3.005
To keep this page light, the plots are shown once, under the R tab.
95% intervals
| Interval | Lower | Upper |
|---|---|---|
| BCa (bias-corrected and accelerated) | 36.779 | 48.772 |
| Percentile | 36.414 | 48.269 |
| Basic | 35.990 | 47.845 |
| Normal | 36.208 | 47.988 |
Bootstrap distribution
| Quantity | Value |
|---|---|
| Resamples (B) | 1,999 |
| SE | 3.005 |
| Bias | 0.0310 |
| Bias correction z₀ | 0.0245 |
| Acceleration a | 0.0190 |
- 37 of 153 rows were left out because a value was missing.
- Seed 42: the same resamples in Python and R (portable Wichmann–Hill stream).
- BCa corrects the percentile interval for bias and skewness (acceleration from the jackknife); prefer it unless n is very small.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Mean one sampleairquality · outcome: Ozone
- Median two groupstoothgrowth · group: supp · outcome: len
- Trimmed booleanmtcars · group: manual · outcome: mpg
- Sd normals1_survey · outcome: pulse rate
- Degenerate n1airquality · outcome: Ozone
In the guides
Where it sits in the decision guides
- Continuous: mean, median, SD, IQR · Statistics Guide · A — Describe data
- Remedies and sensitivity analyses · Statistics Guide · Step 3 — If assumptions are violated
- Robust, permutation and exact methods · Statistics Guide · Step 3 — If assumptions are violated
- Bootstrap · Statistics Guide · Step 3 — If assumptions are violated
What you need
- Outcomenumeric · 1 column
- The numeric variable you are analyzing.
- Two groups (optional)categorical / boolean · 0–1 column · 2–2 levels
- With two groups the interval is for the difference, first level − second level.
Choices you make
statistics
- Statisticdefault mean
The statistic to bootstrap: mean, median, trimmed mean or standard deviation.
- Mean(default) — Bootstraps the mean; pick it for an interval around the average.
- Median — Bootstraps the median; pick it for skewed data or outliers.
- Trimmed mean — Bootstraps the trimmed mean; a middle ground between mean and median.
- Standard deviation — Bootstraps the standard deviation; pick it for an interval around the spread.
- Trimming proportiondefault 0.2
Share trimmed from each end for the trimmed mean (0.2 trims 20% from each tail).
- Intervaldefault bca
All four are reported; this one leads the summary.
- BCa (recommended)(default) — Corrects for bias and skew in the bootstrap distribution; the best general choice, given enough resamples.
- Percentile — Takes the middle of the bootstrap distribution; easy to read, but off when the statistic is biased.
- Basic — Reflects the percentile interval around the estimate; handles some bias, but it can suffer under skew.
- Normal — Estimate ± z × bootstrap SE; use it when the bootstrap distribution looks normal.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
options
- Resamples (B)default 9999
9,999 is plenty for 95% intervals; more makes the interval ends stabler, not narrower.
What it reports
- estimate
- How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
- ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- b
- How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
- n
- How many independent units the analysis used; it sets precision and power.
- se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- bias
- How far an estimator's average answer over many samples sits from the true value.
- z0
- Estimates uncertainty by recomputing a statistic on many samples drawn with replacement from your data.
- accel
- Estimates uncertainty by recomputing a statistic on many samples drawn with replacement from your data.
- perc_low
- A range of effect values compatible with your data at the chosen confidence level.
- perc_high
- A range of effect values compatible with your data at the chosen confidence level.
- basic_low
- A range of effect values compatible with your data at the chosen confidence level.
- basic_high
- A range of effect values compatible with your data at the chosen confidence level.
- norm_low
- A range of effect values compatible with your data at the chosen confidence level.
- norm_high
- A range of effect values compatible with your data at the chosen confidence level.
- bca_low
- A range of effect values compatible with your data at the chosen confidence level.
- bca_high
- A range of effect values compatible with your data at the chosen confidence level.
- statistic_label
- Which statistic was bootstrapped: the mean, median, standard deviation or a trimmed mean.
- ci_type_label
- A range of effect values compatible with your data at the chosen confidence level.
- two_groups
- True when the estimate is a difference between two groups (first minus second), false for a single sample.
- level_1
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- level_2
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- n_1
- How many independent units the analysis used; it sets precision and power.
- n_2
- How many independent units the analysis used; it sets precision and power.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines resample with the same Wichmann–Hill stream (codesplash.stats.rng ↔ cs_rng), so the replicates are identical; intervals agree to floating-point rounding.
The exact script CodeSplash ran for example “Mean one sample” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Bootstrap confidence interval
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bootstrap.ci 1.0.1 · spec 6b94bf8e7cbb3f07
# Dataset: airquality (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import bootstrap as csb
# %% Data
df = pd.read_parquet("tests/parity/fixtures/airquality.parquet", columns=["Ozone"])
n_input = len(df)
df = df.dropna(subset=["Ozone"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["Ozone"]) # infinite values stop the run (registry/errors.yaml)
# %% Bootstrap
y = "Ozone"
x = df[y].to_numpy(dtype=float)
g, levels, codes = None, [], None
if x.size < 2: # the jackknife (BCa acceleration) needs a value left after leaving one out
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A bootstrap interval", min=2, n=int(x.size))
name = "mean"
trim = 0.2
b = int(1999)
ci_type = "bca"
conf = 0.95
seed = 42 # portable Wichmann–Hill stream: R draws the same resamples for this seed
stat = csb.statistic(name, trim)
theta = csb.estimate(x, codes, stat)
t = csb.replicates(x, codes, stat, b, seed) # resampling within groups when there are two
jack = csb.jackknife(x, codes, stat) # leave-one-out values for the BCa acceleration
ci = csb.intervals(theta, t, jack, conf)
if x.size > 20000:
warnings.append("Large sample: the jackknife for the BCa acceleration recomputes the statistic n times.")
# %% Result
stat_label = {"mean": "mean", "median": "median", "sd": "standard deviation", "trimmed": f"{trim:.0%} trimmed mean"}[name]
type_label = {"bca": "BCa", "percentile": "percentile", "basic": "basic", "normal": "normal"}[ci_type]
key = {"bca": "bca", "percentile": "perc", "basic": "basic", "normal": "norm"}[ci_type]
lo, hi = ci[f"{key}_low"], ci[f"{key}_high"]
values = {
"estimate": theta, "ci_low": lo, "ci_high": hi, "b": b, "n": int(x.size),
**{k: v for k, v in ci.items()},
"statistic_label": stat_label, "ci_type_label": type_label, "two_groups": g is not None,
"level_1": levels[0] if g else "", "level_2": levels[1] if g else "",
"n_1": int((codes == 0).sum()) if g else int(x.size), "n_2": int((codes == 1).sum()) if g else 0,
}
pct = f"{conf:.0%}"
what = f"{stat_label} of {y}" + (f": {levels[0]} − {levels[1]}" if g else "")
rows = np.unique(np.round(np.linspace(0, b - 1, min(b, 5000))).astype(int))
cs.publish({
"method": "bootstrap.ci",
"methodVersion": "1.0.1",
"title": "Bootstrap confidence interval",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": int(x.size),
"summary": f"Bootstrap {what}: {theta:.4g}, {pct} {type_label} CI [{lo:.4g}, {hi:.4g}] ({b:,} resamples).",
"apa": f"{cs.fmt_num(theta)}, {pct} {type_label} CI [{cs.fmt_num(lo)}, {cs.fmt_num(hi)}]",
"statistics": [{"key": "estimate", "label": what[0].upper() + what[1:], "value": theta},
{"key": "ci", "label": f"{pct} {type_label} CI", "value": [lo, hi]},
{"key": "se", "label": "Bootstrap SE", "value": ci["se"]}],
"tables": [{"key": "intervals", "title": f"{pct} intervals", "columns": [
{"key": "type", "label": "Interval", "type": "string"}, {"key": "low", "label": "Lower", "type": "number"},
{"key": "high", "label": "Upper", "type": "number"}],
"rows": [{"type": "BCa (bias-corrected and accelerated)", "low": ci["bca_low"], "high": ci["bca_high"]},
{"type": "Percentile", "low": ci["perc_low"], "high": ci["perc_high"]},
{"type": "Basic", "low": ci["basic_low"], "high": ci["basic_high"]},
{"type": "Normal", "low": ci["norm_low"], "high": ci["norm_high"]}]},
{"key": "diagnostics", "title": "Bootstrap distribution", "columns": [
{"key": "k", "label": "Quantity", "type": "string"}, {"key": "v", "label": "Value", "type": "number"}],
"rows": [{"k": "Resamples (B)", "v": b}, {"k": "SE", "v": ci["se"]}, {"k": "Bias", "v": ci["bias"]},
{"k": "Bias correction z₀", "v": ci["z0"]}, {"k": "Acceleration a", "v": ci["accel"]}]}],
"effectSizes": [],
"assumptions": [],
"warnings": warnings,
"notes": [f"Seed {seed}: the same resamples in Python and R (portable Wichmann–Hill stream)."
+ (" Resampling is within groups." if g else ""),
"BCa corrects the percentile interval for bias and skewness (acceleration from the jackknife); prefer it unless n is very small."],
"charts": [cs.chart("replicates", "histogram", f"Bootstrap distribution of the {stat_label}", {"x": cs.col(f"Bootstrap {stat_label}", np.asarray(t)[rows])})],
"values": values,
})
The exact script CodeSplash ran for example “Mean one sample” · R version 4.5.1 (2025-06-13)
# Bootstrap confidence interval
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bootstrap.ci 1.0.1 · spec 6b94bf8e7cbb3f07
# Dataset: airquality (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/airquality.parquet", col_select = c("Ozone")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Ozone")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("Ozone")) # infinite values stop the run (registry/errors.yaml)
# %% Bootstrap
y <- "Ozone"
x <- as.numeric(df[[y]])
g <- NULL
levels_g <- character(0)
codes <- NULL
if (length(x) < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A bootstrap interval", min = 2, n = length(x)) # the jackknife needs a value left
name <- "mean"
trim <- 0.2
b <- as.integer(1999)
ci_type <- "bca"
conf <- 0.95
seed <- 42 # portable Wichmann-Hill stream: Python draws the same resamples for this seed
stat <- cs_boot_statistic(name, trim)
theta <- cs_boot_estimate(x, codes, stat)
t <- cs_boot_replicates(x, codes, stat, b, seed) # resampling within groups when there are two
jack <- cs_boot_jackknife(x, codes, stat) # leave-one-out values for the BCa acceleration
ci <- cs_boot_intervals(theta, t, jack, conf)
if (length(x) > 20000) warnings <- c(warnings, "Large sample: the jackknife for the BCa acceleration recomputes the statistic n times.")
# %% Result
stat_label <- switch(name, mean = "mean", median = "median", sd = "standard deviation", trimmed = sprintf("%.0f%% trimmed mean", trim * 100))
type_label <- switch(ci_type, bca = "BCa", percentile = "percentile", basic = "basic", normal = "normal")
key <- switch(ci_type, bca = "bca", percentile = "perc", basic = "basic", normal = "norm")
lo <- ci[[paste0(key, "_low")]]
hi <- ci[[paste0(key, "_high")]]
values <- c(
list(estimate = theta, ci_low = lo, ci_high = hi, b = b, n = length(x)),
ci,
list(statistic_label = stat_label, ci_type_label = type_label, two_groups = !is.null(g),
level_1 = if (!is.null(g)) levels_g[1] else "", level_2 = if (!is.null(g)) levels_g[2] else "",
n_1 = if (!is.null(g)) sum(codes == 0) else length(x), n_2 = if (!is.null(g)) sum(codes == 1) else 0)
)
pct <- sprintf("%.0f%%", conf * 100)
what <- paste0(stat_label, " of ", y, if (!is.null(g)) sprintf(": %s − %s", levels_g[1], levels_g[2]) else "")
rows <- unique(round(seq(1, b, length.out = min(b, 5000))))
cs_publish(list(
method = "bootstrap.ci",
methodVersion = "1.0.1",
title = "Bootstrap confidence interval",
engine = cs_engine_info("stats", "nanoparquet"),
n = length(x),
summary = sprintf("Bootstrap %s: %.4g, %s %s CI [%.4g, %.4g] (%s resamples).", what, theta, pct, type_label, lo, hi, format(b, big.mark = ",")),
apa = sprintf("%s, %s %s CI [%s, %s]", cs_fmt_num(theta), pct, type_label, cs_fmt_num(lo), cs_fmt_num(hi)),
statistics = list(list(key = "estimate", label = paste0(toupper(substr(what, 1, 1)), substring(what, 2)), value = theta),
list(key = "ci", label = paste(pct, type_label, "CI"), value = c(lo, hi)),
list(key = "se", label = "Bootstrap SE", value = ci$se)),
tables = list(
list(key = "intervals", title = paste(pct, "intervals"), columns = list(
list(key = "type", label = "Interval", type = "string"), list(key = "low", label = "Lower", type = "number"),
list(key = "high", label = "Upper", type = "number")),
rows = list(list(type = "BCa (bias-corrected and accelerated)", low = ci$bca_low, high = ci$bca_high),
list(type = "Percentile", low = ci$perc_low, high = ci$perc_high),
list(type = "Basic", low = ci$basic_low, high = ci$basic_high),
list(type = "Normal", low = ci$norm_low, high = ci$norm_high))),
list(key = "diagnostics", title = "Bootstrap distribution", columns = list(
list(key = "k", label = "Quantity", type = "string"), list(key = "v", label = "Value", type = "number")),
rows = list(list(k = "Resamples (B)", v = b), list(k = "SE", v = ci$se), list(k = "Bias", v = ci$bias),
list(k = "Bias correction z₀", v = ci$z0), list(k = "Acceleration a", v = ci$accel)))
),
effectSizes = list(),
assumptions = list(),
warnings = warnings,
notes = list(paste0(sprintf("Seed %s: the same resamples in Python and R (portable Wichmann–Hill stream).", format(seed)),
if (!is.null(g)) " Resampling is within groups." else ""),
"BCa corrects the percentile interval for bias and skewness (acceleration from the jackknife); prefer it unless n is very small."),
charts = list(cs_chart("replicates", "histogram", sprintf("Bootstrap distribution of the %s", stat_label),
list(x = cs_col(sprintf("Bootstrap %s", stat_label), t[rows])))),
values = values
))
Sources
- Efron, B., & Tibshirani, R. J. (1993). An introduction to the bootstrap. Chapman & Hall.
- Davison, A. C., & Hinkley, D. V. (1997). Bootstrap methods and their application. Cambridge University Press.
- Wichmann, B. A., & Hill, I. D. (1982). Algorithm AS 183: An efficient and portable pseudo-random number generator. Applied Statistics, 31, 188–190.
From the CodeSplash method registry · bootstrap.ci v1.0.1.