Bootstrapping a confidence interval in Python
Resampling gives an interval for any statistic, with no formula needed.
import numpy as np
from scipy import stats
rng = np.random.default_rng(5)
sample = rng.normal(95, 12, size=60)
result = stats.bootstrap((sample,), np.median, n_resamples=2000,
confidence_level=0.95, random_state=rng)
low, high = result.confidence_interval
print(round(np.median(sample), 2), round(low, 2), round(high, 2))
print(round(result.standard_error, 3))
perm = stats.permutation_test((sample, sample + 3),
lambda a, b: np.mean(a) - np.mean(b),
n_resamples=500, random_state=rng)
print(round(perm.pvalue, 4))
How it works
- The data goes in as a one-element tuple of samples.
statisticis any function reducing a sample to a number.confidence_levelandn_resamplescontrol the result.
Keywords and builtins used here
aslambdaprintround
The run, in numbers
- Lines
- 16
- Characters to type
- 517
- Tokens
- 157
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 90 seconds.
Step 2 of 2 in Correlation & resampling, step 9 of 23 in Scientific computing with SciPy.