Intervals in Code
Scipy t interval.
With small samples, one point nine six is a little too optimistic, because we also estimated the standard deviation. The fix is the t distribution, which has slightly fatter tails. Sci Pi makes it one line.

- Small samples need care
- The t distribution
- One line with SciPy
A t interval
A coffee shop times twelve orders, in minutes. Stats dot t dot interval takes the confidence level, the degrees of freedom, which is N minus one, the sample mean, and the standard error. Sem computes the standard error. Run it. The true average wait is probably between about three point nine and four point nine minutes.
import numpy as np
from scipy import stats
waits = np.array([4.1, 3.5, 5.2, 4.8, 3.9, 4.4, 6.0, 3.2, 4.7, 5.1, 3.8, 4.3])
low, high = stats.t.interval(0.95, len(waits) - 1,
loc=waits.mean(), scale=stats.sem(waits))
print(f"mean {waits.mean():.2f}, 95% CI {low:.2f} to {high:.2f}")mean 4.42, 95% CI 3.91 to 4.92
Wider or narrower
Three things change an interval's width. More data makes it narrower. More spread in the data makes it wider. And asking for more confidence, like ninety nine percent instead of ninety five, makes it wider too. To be more sure, you have to give a wider range.
| key | value |
|---|---|
| More data | narrower |
| More spread | wider |
| 99% instead of 95% | wider |
| Small n | use the t distribution |
Summary
Use the t distribution for confidence intervals, especially with small samples. Sci Pi's t dot interval does it in one line. Next, the bootstrap.
Key takeaways- stats.t.interval
- stats.sem
- df = n − 1