Statistical modeling with Python · Lesson 5 of 16
Hypothesis tests in Python: t-tests
Run one-sample, two-sample (Welch) and paired t-tests with scipy.stats, and read p-values honestly: what they say and what they do not.
A hypothesis test asks: could the difference I see be just chance? You start from a boring claim, the null hypothesis ("the machine fills 500 ml on average", "the two teaching methods give the same mean mark"), and measure how surprising your data would be if it were true.
That measure is the p-value. Each test below prints it with the small helper show_p, which writes very small values as "p < 0.001" instead of a long number.
One-sample t-test: is the mean equal to a target?
A machine should fill bottles with 500 ml. We measured 12 bottles. ttest_1samp compares their mean with 500.
def show_p(p):
return "p < 0.001" if p < 0.001 else f"p = {p:.3f}"
from scipy import stats
ml = [498.2, 499.1, 497.8, 500.4, 498.9, 497.5,
499.6, 498.0, 499.3, 498.4, 500.1, 497.9]
res = stats.ttest_1samp(ml, popmean=500)
print(f"mean: {sum(ml) / len(ml):.2f} ml")
print(f"t = {res.statistic:.2f}, {show_p(res.pvalue)}")mean: 498.77 ml t = -4.51, p < 0.001
How to read it: the bottles average 498.77 ml. The t statistic says how many standard errors the mean is from 500 (−4.5, far). The p-value is tiny: if the machine really averaged 500 ml, a sample this far off would almost never happen. So we have strong evidence that it under-fills.
What a p-value is, and what it is not
- It is the probability of getting a result at least this extreme if the null hypothesis were true.
- It is not the probability that the null hypothesis is true, and 1 − p is not the probability that your idea is right.
- It is not a measure of size. With huge samples a tiny, useless difference gets p < 0.001. Always report the difference itself and its confidence interval.
- p > 0.05 does not prove "no difference": it only says this sample cannot tell. Small samples often cannot.
- The 0.05 line is a convention, not a law of nature. p = 0.049 and p = 0.051 are practically the same evidence.
Two-sample t-test: do two groups differ?
Two classes learned with different methods. ttest_ind compares the mean marks. Pass equal_var=False for Welch's t-test, which does not assume both groups vary equally. SciPy's default (equal_var=True) is Student's t-test, which does assume equal spreads, so Welch has to be asked for; it is the safer choice.
def show_p(p):
return "p < 0.001" if p < 0.001 else f"p = {p:.3f}"
import numpy as np
from scipy import stats
method_a = np.array([62, 71, 58, 66, 74, 69, 63, 70, 65, 68])
method_b = np.array([70, 78, 66, 75, 81, 72, 69, 77, 74, 79])
res = stats.ttest_ind(method_b, method_a, equal_var=False)
low, high = res.confidence_interval(0.95)
print(f"difference in means: {method_b.mean() - method_a.mean():.1f} marks")
print(f"95% CI of the difference: {low:.1f} to {high:.1f}")
print(f"t = {res.statistic:.2f}, {show_p(res.pvalue)}")difference in means: 7.5 marks 95% CI of the difference: 3.0 to 12.0 t = 3.50, p = 0.003
Method B scores 7.5 marks higher on average, plausibly between about 3 and 12. The p-value (0.003) says a gap this large would be rare if the methods were equally good. The interval tells you how much better, which is what a teacher actually needs.
Paired t-test: the same people measured twice
When each person is measured before and after (blood pressure, reaction time), the two columns are linked. ttest_rel tests the differences within each person, which is much more sensitive than treating the columns as separate groups.
def show_p(p):
return "p < 0.001" if p < 0.001 else f"p = {p:.3f}"
import numpy as np
from scipy import stats
before = np.array([142, 138, 150, 145, 160, 139, 148, 155])
after = np.array([138, 136, 144, 145, 151, 137, 142, 149])
diff = after - before
print("differences:", diff)
res = stats.ttest_rel(after, before)
print(f"mean change: {diff.mean():.2f}, {show_p(res.pvalue)}")
res_wrong = stats.ttest_ind(after, before)
print(f"if we wrongly ignore the pairs: {show_p(res_wrong.pvalue)}")differences: [-4 -2 -6 0 -9 -2 -6 -6] mean change: -4.38, p = 0.004 if we wrongly ignore the pairs: p = 0.214
alternative="greater" (first group larger) or "less". Decide this before you look at the data, not after.✎ Exercise
A gym measured 8 members' 5 km times (minutes) before and after a training plan. Run a paired t-test of after against before and print the mean change (2 decimals) and the p-value with 3 decimals.
Hint: stats.ttest_rel(after, before) returns an object with .statistic and .pvalue.
import numpy as np
from scipy import stats
before = np.array([31.5, 28.2, 35.0, 30.1, 33.4, 29.8, 32.6, 34.1])
after = np.array([30.2, 27.9, 33.1, 29.5, 32.8, 28.1, 31.9, 32.5])
# your code here
Expected output:
mean change: -1.09 p = 0.001
Show a solution
import numpy as np
from scipy import stats
before = np.array([31.5, 28.2, 35.0, 30.1, 33.4, 29.8, 32.6, 34.1])
after = np.array([30.2, 27.9, 33.1, 29.5, 32.8, 28.1, 31.9, 32.5])
res = stats.ttest_rel(after, before)
print(f"mean change: {(after - before).mean():.2f}")
print(f"p = {res.pvalue:.3f}")mean change: -1.09 p = 0.001
Check yourself
1. A test gives p = 0.03. What does that mean?
A p-value is computed assuming the null hypothesis; it is not the probability of the null hypothesis.
2. A study with 8 people finds p = 0.40. What can you conclude?
Absence of evidence is not evidence of absence, especially with small samples.
3. Which test fits blood pressure measured on the same patients before and after a drug?
The measurements are paired, so test the within-person differences with ttest_rel.