DS Hypothesis Testing
The regression p-values you've met are one kind of hypothesis test. The same logic answers many everyday business questions directly: Did the new pricing change anything? Are two stations really different, or is it noise?
The recipe
- State a null hypothesis H₀ ("no difference") and an alternative H₁ ("there is a difference").
- Choose a significance level α, usually 0.05, before looking at the result.
- Compute a test statistic from the data and its p-value: the probability of a result at least this extreme if H₀ were true.
- If
p < α, reject H₀. Otherwise, you fail to reject it — not the same as proving it.
Comparing two groups: the t-test
Are weekends really busier, or could the difference in means be chance? A two-sample t-test compares the means of two groups. Welch's version (equal_var=False) doesn't assume equal spreads and is the safer default:
import numpy as np
import pandas as pd
from scipy import stats
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
wkend = bikes.loc[bikes["weekend"] == 1, "rides"]
wkday = bikes.loc[bikes["weekend"] == 0, "rides"]
print(f"weekend mean {wkend.mean():.1f} (n={len(wkend)}), weekday mean {wkday.mean():.1f} (n={len(wkday)})")
result = stats.ttest_ind(wkend, wkday, equal_var=False)
print(f"t = {result.statistic:.2f}, p = {result.pvalue:.4f}")weekend mean 432.5 (n=16), weekday mean 327.4 (n=44)
t = 3.77, p = 0.0008
The p-value is far below 0.05: a difference of about 105 rides would be very unlikely if weekends and weekdays had the same true mean.
Note: The t-test compares raw means. Part of the weekend advantage could come from the weather (weekends happened to be a little warmer). Regression with temperature and rain in the model, as in the Linear Regression Case, separates the two.
An experiment: does a discount work?
Riverside Bikes runs a real randomised experiment: for four weeks, 12 of its 24 stations — chosen by lot — offer 20 % off. Then it compares the average daily rides per station:
import numpy as np
from scipy import stats
rng = np.random.default_rng(2020)
control = rng.normal(52, 9, 12).round(1) # average daily rides per station, no discount
discount = rng.normal(57, 9, 12).round(1) # with the discount
print("control: ", control)
print("discount:", discount)
diff = discount.mean() - control.mean()
t = stats.ttest_ind(discount, control, equal_var=False)
print(f"difference in means: {diff:.1f} rides/day, p = {t.pvalue:.3f}")control: [63.3 54. 64. 39.2 49.5 52.6 54.3 54.5 36.2 61.8 46.9 57.3]
discount: [60.5 61. 57.8 69. 48.9 52.7 49.6 83.8 67.7 52.4 38.9 57.6]
difference in means: 5.5 rides/day, p = 0.202
Discount stations did average about 5 more rides a day, but with only 12 stations per group and station-to-station variation of about 9 rides, that's within what chance produces: p ≈ 0.2, so we can't reject H₀. This doesn't prove the discount does nothing — the experiment may simply be too small to detect a modest effect.
Effect size, confidence interval and power
A p-value alone hides the most important information: how big is the effect and how precisely do we know it?
import numpy as np
from scipy import stats
rng = np.random.default_rng(2020)
control = rng.normal(52, 9, 12).round(1)
discount = rng.normal(57, 9, 12).round(1)
diff = discount.mean() - control.mean()
se = np.sqrt(discount.var(ddof=1) / 12 + control.var(ddof=1) / 12)
dof = 22 # simple approximation: n1 + n2 - 2
margin = stats.t.ppf(0.975, dof) * se
print(f"difference: {diff:.1f} 95% CI [{diff - margin:.1f}, {diff + margin:.1f}]")
# How often would an experiment of this size detect a true +5 effect? Simulate it.
sim = np.random.default_rng(0)
hits = 0
for _ in range(2000):
c = sim.normal(52, 9, 12)
d = sim.normal(57, 9, 12)
hits += stats.ttest_ind(d, c, equal_var=False).pvalue < 0.05
print(f"power with 12 stations per group: {hits / 2000:.0%}")difference: 5.5 95% CI [-3.2, 14.2]
power with 12 stations per group: 23%
The confidence interval runs from a small loss to a sizeable gain — consistent with no effect and with a useful one. The simulated power shows the experiment detects a true +5 effect only about a quarter of the time. A bigger or longer experiment is needed before deciding.
Other common tests
| Question | Test | SciPy |
|---|---|---|
| Two group means | Welch t-test | stats.ttest_ind(a, b, equal_var=False) |
| Same units measured twice (before/after) | paired t-test | stats.ttest_rel(before, after) |
| Three or more group means | one-way ANOVA | stats.f_oneway(a, b, c) |
| Two groups, skewed data | Mann-Whitney U | stats.mannwhitneyu(a, b) |
| Two categorical variables independent? | chi-square | stats.chi2_contingency(table) |
| Is a correlation non-zero? | Pearson test | stats.pearsonr(x, y) |
For example, are members and casual riders equally likely to ride on rainy days? A chi-square test on a table of counts answers that:
import numpy as np
from scipy import stats
# dry days wet days
table = np.array([[820, 310], # members
[640, 150]]) # casual riders
res = stats.chi2_contingency(table)
print(f"chi2 = {res.statistic:.1f}, p = {res.pvalue:.2e}")
print("share of trips on wet days: members", round(310 / 1130, 3), "casual", round(150 / 790, 3))chi2 = 17.7, p = 2.52e-05
share of trips on wet days: members 0.274 casual 0.19
Members are much more likely to ride in the rain (27 % vs 19 % of their trips), and the tiny p-value says this difference in proportions isn't chance.
Test yourself
A test gives p = 0.21. What should you conclude at α = 0.05?
- H₀ is true
- Fail to reject H₀: no convincing evidence of a difference
- Reject H₀
- The effect is 21 %
What is the statistical **power** of an experiment?
- The probability H₀ is true
- The probability of detecting a real effect of a given size
- The effect size
- The sample mean
Which test fits "Are wet-day trips equally common for members and casual riders?" given a table of counts?
- Paired t-test
- Chi-square test of independence
- Pearson correlation
- Linear regression on dates