Section 4 · Lesson 1
Hypothesis tests, p-values and the t-test
Frame a null hypothesis, read a p-value correctly, and compare two means with a permutation test and Welch's t-test.
Variant B’s revenue per user is about $1.28 higher than A’s. Before anyone ships the new page, someone has to ask: is that real, or could random assignment alone produce a gap like that? A hypothesis test is a disciplined way to answer.
The logic, step by step
- Null hypothesis (H0): the boring explanation. “The page makes no difference; the true means are equal and any gap is chance.”
- Alternative hypothesis (H1): what you suspect. “The means differ” (two-sided) or “B’s mean is higher” (one-sided).
- Test statistic: one number measuring how far the data are from what H0 predicts. For two
means it is the difference divided by its standard error:
t = (mean_B - mean_A) / sqrt(s_A**2 / n_A + s_B**2 / n_B) - p-value: assuming H0 is true, the probability of a test statistic at least as extreme as the one you observed.
- Decision: pick a significance level α before looking (0.05 is common). If p ≤ α, reject H0 (“statistically significant”). Otherwise, you fail to reject H0.
Shuffling makes it concrete
If the variant truly doesn’t matter, the A/B labels are arbitrary. So shuffle them, recompute the difference, and repeat thousands of times. That gives the distribution of differences you’d see under H0. The share of shuffled differences at least as large as the real one is a p-value (a permutation test). The t-test reaches nearly the same answer with a formula.
What a p-value is not
- It is not the probability that H0 is true, or that the result is “due to chance”.
- 1 - p is not the probability that B is better.
- It says nothing about the size of the effect. With huge samples, trivial differences get tiny p-values.
- p > 0.05 is not proof of no effect. It means the data can’t rule out “no effect”; the test may simply have been too small.
Errors and one- vs two-sided tests
A Type I error is a false positive (rejecting a true H0); α is its rate. A Type II error is a false negative (missing a real effect); bigger samples reduce it, which is what statistical power measures.
Choose one- or two-sided before you see the data. A one-sided test only looks for an effect in one direction; when the effect goes that way, its p-value is half the two-sided p-value. Switching to one-sided after peeking at the results is cheating. Two-sided is the safe default.
Two-sample t-tests in SciPy
from scipy import stats
stats.ttest_ind(b, a, equal_var=False) # Welch's t-test (two-sided)
stats.ttest_ind(b, a, equal_var=False, alternative="greater") # H1: mean(b) > mean(a)
stats.ttest_ind(b, a) # Student's pooled t-test
Student’s pooled test assumes both groups have the same variance. Welch’s test does not,
and it loses almost nothing when variances are equal, so use it as your default. Be careful:
SciPy’s default is equal_var=True. For before/after measurements on the same units (the
same campaigns in two months), use the paired test, stats.ttest_rel.
Revenue per user is mostly zeros with a long tail, far from normal. The t-test still works here because, with about 2,000 users per group, the sample means are close to normal (the CLT).
In the real world
- Don’t peek and stop. Checking results every day and stopping the first time p < 0.05 inflates false positives far above 5%. Fix the sample size or duration in advance.
- Many metrics, many chances. Test 20 independent metrics with no real effect and you expect about one “significant” result by luck. Name one primary metric up front.
- Significant isn’t the same as important. Pair every p-value with the effect size and a confidence interval, then ask whether the lift pays for the change.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
A p-value by shuffling
DoneIn ab_test.csv, variant B's average revenue per user is higher than A's. Could that be luck? Simulate the null hypothesis ("the variant label doesn't matter") by shuffling labels.
observed_diff: mean revenue of B minus mean revenue of Aperm_diffs: 2,000 shuffled differences. Userng = np.random.default_rng(42); in each
round, shuffle the B/A labels with rng.permutation(is_b) and compute mean revenue of the "B" rows minus mean revenue of the "A" rows
perm_p: the two-sided permutation p-value, the share of shuffled differences whose
absolute value is at least abs(observed_diff)
No rounding needed. Your perm_p will be close to (not exactly) the t-test's p-value.
Need a hint?
revenue[is_b].mean()averages B users;~is_bflips True/False to select A users.rng.permutation(is_b)returns a shuffled copy: same number of B labels, assigned to random users.np.mean(np.abs(perm_diffs) >= abs(observed_diff))is the two-sided p-value.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import numpy as np
import pandas as pd
ab = pd.read_csv("ab_test.csv")
revenue = ab["revenue"].to_numpy()
is_b = (ab["variant"] == "B").to_numpy() # True for B users, False for A
rng = np.random.default_rng(42)
observed_diff = None
perm_diffs = []
# TODO: 2,000 rounds of shuffling is_b and recomputing the difference
perm_p = None
print(observed_diff, perm_p)
Files in the working directory
ab_test.csv (4,000 rows)daily_stats.csv (1,561 rows)orders.csv (900 rows)campaigns.csv (40 rows)Welch's t-test on revenue per user
DoneCompare revenue per user between B and A with Welch's t-test (scipy.stats.ttest_ind(b_rev, a_rev, equal_var=False)), passing B first.
t_stat: the t statistic, rounded to 3 decimalsp_two_sided: the two-sided p-value (the default), rounded to 4 decimalsp_one_sided: the one-sided p-value for "B's mean is greater than A's"
(alternative="greater"), rounded to 4 decimals
Note: SciPy's default is equal_var=True (the pooled Student's t-test). Set it to False.
Need a hint?
stats.ttest_ind(x, y, equal_var=False)returns a result with.statisticand.pvalue.alternative="greater"tests whether the mean of the first sample is greater than the second.- When the observed effect is in the predicted direction, the one-sided p-value is half the two-sided one.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
from scipy import stats
ab = pd.read_csv("ab_test.csv")
a_rev = ab.loc[ab["variant"] == "A", "revenue"]
b_rev = ab.loc[ab["variant"] == "B", "revenue"]
result = stats.ttest_ind(b_rev, a_rev) # pooled test: not what we want
t_stat = None
p_two_sided = None
p_one_sided = None
print(t_stat, p_two_sided, p_one_sided)
Files in the working directory
ab_test.csv (4,000 rows)daily_stats.csv (1,561 rows)orders.csv (900 rows)campaigns.csv (40 rows)Bigger orders, or more of them?
DoneB earns more revenue per user. Is that because B's converters spend more per order? Keep only users with converted == 1 and compare their revenue between B and A with a two-sided Welch t-test (B first).
aov_diff: mean revenue of B converters minus A converters, rounded to 2 decimalsp_aov: the two-sided Welch p-value, rounded to 4 decimalsreject_null:Trueifp_aov < 0.05, elseFalse
Need a hint?
ab[ab["converted"] == 1]keeps only converters.- A comparison like
p_aov < 0.05already gives True/False; wrap it inbool()to get a plain Python bool.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
from scipy import stats
ab = pd.read_csv("ab_test.csv")
conv = ab # TODO: keep converters only
aov_diff = None
p_aov = None
reject_null = None
print(aov_diff, p_aov, reject_null)
Files in the working directory
ab_test.csv (4,000 rows)daily_stats.csv (1,561 rows)orders.csv (900 rows)campaigns.csv (40 rows)