A Real T-Test with SciPy
20 min
Statistics' hypothesis-testing module used a z-test
(statistics.NormalDist) specifically because Python's standard library
has no t-distribution implementation — noted at the time as a deliberate
simplification, accurate for large samples but not the textbook-standard
choice for small ones. scipy.stats closes that exact gap: a real
Student's t-distribution, and a one-line function for the most common
test.
from scipy import stats
def one_sample_ttest(sample, popmean):
t_statistic, p_value = stats.ttest_1samp(sample, popmean)
return (round(t_statistic, 4), round(p_value, 4))
This is the real, textbook-standard t-test — the exact test Statistics' own course had to approximate with a z-test due to a genuine stdlib limitation, now available in one function call once scipy is in play.
Write `one_sample_ttest(sample, popmean)`: use `scipy.stats.ttest_1samp` to test whether `sample`'s mean differs from `popmean`. Return `(t_statistic, p_value)`, each rounded to 4 decimal places.
Statistics' own hypothesis-testing module had to use a z-test instead of a t-test, and explicitly noted why. What was that reason?
You can run a real one-sample t-test with scipy.stats, closing the exact gap the pure-stdlib Statistics course had to work around.