10.1. A/B Testing#
An A/B test randomly assigns units, such as customers or website visitors, to one of two conditions and compares an outcome, the measured result used to compare the groups, such as whether a visitor buys. It is the most common business experiment: a structured test run to support a management decision. A manager might show half of the visitors one checkout page and half another, then compare how many in each group buy. Any analysis that compares an outcome between two groups is a two-sample comparison. Comparing groups that already exist uses similar calculations, but the way the groups were formed decides whether the result supports a causal claim. That difference is the theme of this chapter.
In Assessing a Model with Simulation and Comparing Distributions you tested a chance model against one sample. Here you compare two groups. The method is a permutation test: if the version has no effect, then which visitor saw which page is just a label, and you can shuffle the labels to see what chance alone produces.
Run the demonstration cells in order, including the setup. Each Interactive Exercise includes its own setup and can run independently.
10.1.1. Two Kinds of Randomness#
Two different random processes appear in data work, each answering a different question.
Random sampling chooses which units enter a study from a larger population. If a company picks 200 customers at random from its list of 50,000, those 200 tend to resemble the whole list. Sampling supports generalizing: what you see in the sample is likely to hold, up to sampling variability, for the population (see Sampling Variability).
Random assignment decides which condition each chosen unit receives. If the company then flips a coin for each of the 200 customers to decide whether they see page A or page B, the two groups differ only by chance at the start. Assignment supports a causal comparison: a later difference between groups is likely due to the page, or to chance, and not to who happened to be in each group.
A study can use one, both, or neither. Both steps use a random number generator, and the two calls below do the work in this chapter.
The general pattern (a template, not runnable code):
rng = np.random.default_rng(seed)
rng.choice(values, size=n, replace=False) # n different items from values at random
rng.permutation(values) # all of values, in a random order
np.random.default_rng(seed)creates a generator. The sameseedgives the same random results every time, which keeps the chapter’s numbers repeatable.rng.choice()returns a subset:sizeitems fromvalues. Withreplace=Falseno item is picked twice, which is what sampling customers from a list needs.rng.permutation()returns every item ofvalues, reordered. It is the tool for shuffling labels.Both return a new array. The original
valuesstays unchanged.
A small example with five letters shows the difference.
rng = np.random.default_rng(1)
values = np.array(['A', 'A', 'B', 'B', 'C'])
print(values) # the original
print(rng.choice(values, size=2, replace=False)) # two of the five
print(rng.permutation(values)) # all five, reordered
print(values) # still unchanged
['A' 'A' 'B' 'B' 'C']
['A' 'B']
['C' 'A' 'B' 'A' 'B']
['A' 'A' 'B' 'B' 'C']
Now combine them. The code below does both for a small customer list. It first selects 20 customers with rng.choice, then allocates ten A labels and ten B labels among them with rng.permutation.
rng = np.random.default_rng(5)
customer_ids = np.arange(100)
selected = rng.choice(customer_ids, size=20, replace=False) # sampling: who is in the study
labels = np.array(['A'] * 10 + ['B'] * 10)
assigned = rng.permutation(labels) # assignment: who gets which page
study = pd.DataFrame({'customer': selected, 'version': assigned})
print(study.head(6))
print(study['version'].value_counts().sort_index())
customer version
0 87 A
1 66 B
2 44 A
3 95 A
4 12 B
5 97 B
version
A 10
B 10
Name: count, dtype: int64
Sampling picked the 20 customers, and assignment split them into two groups of 10. Whether what you learn from these 20 applies to all 100 customers depends on the first step (sampling). Whether a difference between A and B can be credited to the page, and not to which customers landed in each group, depends on the second step (assignment).
### Exercise: Distinguish Two Random Processes
# A company selects 20 customers from its list, then assigns them to A or B.
# 1. Use ex_rng.choice to select 20 different customer IDs.
# 2. Use ex_rng.permutation to shuffle ten A labels and ten B labels.
# 3. Print the number of distinct selected IDs and the two group sizes.
# Print exactly:
# Selected: 20
# Group A: 10
# Group B: 10
import numpy as np
ex_rng = np.random.default_rng(5)
ex_customer_ids = np.arange(100)
ex_labels = np.array(['A'] * 10 + ['B'] * 10)
### Your code starts here.
### Your code ends here.
Selected: 20
Group A: 10
Group B: 10
10.1.2. The Checkout Experiment#
An online store wants to know whether a redesigned checkout page sells more. It randomly showed each of 10,000 visitors either the current page (version A) or the redesign (version B), 5,000 visitors each. For every visitor the store recorded whether they bought anything and, if so, the order value.
The file checkout_test.csv has one row per visitor: visitor_id, version, purchased (1 if the visitor bought, 0 if not), and order_value (in dollars, blank when the visitor did not buy). The data are simulated for this book: the store is hypothetical, and the file was generated with a known difference between the two pages, so the test has a real effect to find.
checkout = pd.read_csv(path_data + 'checkout_test.csv')
print(checkout.shape)
checkout.head()
(10000, 4)
| visitor_id | version | purchased | order_value | |
|---|---|---|---|---|
| 0 | V00001 | B | 0 | NaN |
| 1 | V00002 | B | 0 | NaN |
| 2 | V00003 | B | 0 | NaN |
| 3 | V00004 | A | 0 | NaN |
| 4 | V00005 | B | 1 | 30.27 |
Because purchased is 1 or 0, its sum counts the buyers, and its mean (the sum divided by the number of visitors) is the share of visitors who bought. This share is the conversion rate. Grouping by version gives the number of visitors, the number of buyers, and the conversion rate for each version.
rates = checkout.groupby('version')['purchased'].agg(['count', 'sum', 'mean'])
rates.columns = ['visitors', 'purchases', 'conversion_rate']
print(rates)
visitors purchases conversion_rate
version
A 5000 400 0.08
B 5000 500 0.10
Version A converted 8.0% of its visitors and version B converted 10.0%. A gap between two rates like these is a difference in proportions, and it can be reported in two ways.
The difference in percentage points subtracts the two rates: 10.0 minus 8.0 is 2.0 percentage points. It says how many more purchases per 100 visitors.
The relative lift divides the difference by the starting rate: 2.0 divided by 8.0 is 25%. It says B’s rate is one quarter higher than A’s.
Both describe the same result. Use percentage points when the audience will turn the difference into counts or revenue (“2 more buyers per 100 visitors”), and use relative lift when comparing across tests with different baseline rates. Write “2.0 percentage points” and not “2%”, which a reader might confuse with the 25% lift.
rate_a = rates.loc['A', 'conversion_rate']
rate_b = rates.loc['B', 'conversion_rate']
print('Difference (B minus A):', round((rate_b - rate_a) * 100, 1), 'percentage points')
print('Relative lift:', round((rate_b - rate_a) / rate_a * 100, 1), 'percent')
Difference (B minus A): 2.0 percentage points
Relative lift: 25.0 percent
In the store’s terms, the redesign sold to 2 more visitors per 100, a 25% lift over the old rate. The open question now is: Could random assignment alone produce a gap this large if the two pages were equally effective?
A permutation test answers that question in four stages.
Stage |
What you do |
What stays fixed |
|
|---|---|---|---|
1 |
Observe |
Compute B minus A using the real labels. |
The recorded visitors and purchases. |
2 |
Simulate |
Rearrange labels and recompute the difference. |
Outcomes and the number of labels in each group. |
3 |
Compare |
Count simulated differences at least as large as observed. |
The alternative and cutoff selected before testing. |
4 |
Interpret |
Connect the evidence to design and business consequences. |
The limits of what was measured. |
These are the four steps of a test from Hypotheses and p-Values, applied to two groups.
### Exercise: Conversion Rates for a Small Test
# A pilot showed version A or B of a page to 16 visitors, 8 each.
# 1. Use groupby to compute the conversion rate for each version.
# 2. Print each rate, the difference (B minus A) in percentage points,
# and the relative lift in percent, both rounded to 1 decimal.
# Print exactly:
# Conversion rate A: 0.25
# Conversion rate B: 0.375
# Difference (B minus A): 12.5 percentage points
# Relative lift: 50.0 percent
import pandas as pd
pilot = pd.DataFrame({
'version': ['A'] * 8 + ['B'] * 8,
'purchased': [1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0],
})
### Your code starts here.
### Your code ends here.
Conversion rate A: 0.25
Conversion rate B: 0.375
Difference (B minus A): 12.5 percentage points
Relative lift: 50.0 percent
10.1.3. Hypotheses and Test Statistic#
The test starts with two competing statements about the population of visitors the store could show a page to.
Null hypothesis: The checkout version has no effect on whether a visitor buys. Each visitor would have made the same decision on either page, so the A and B labels are only tags, and any gap in conversion is due to the chance that visitors landed in one group or the other.
Alternative hypothesis: Version B leads to a higher conversion rate than version A.
The alternative is one-sided. The store would adopt B only if it converts more, and the team decided that before looking at the data. Choosing the direction after seeing the result would make the test too easy to pass.
The test statistic is the conversion rate of B minus the conversion rate of A. Large positive values favor the alternative. Under the null, the statistic should be near zero, with random ups and downs.
The null hypothesis, together with the chance process it implies (here, shuffling the labels), forms the null model: a stated reference model for how group differences could arise by chance alone. Since the labels are interchangeable under the null model, you can generate the statistic’s chance behavior by shuffling the labels. A function makes the calculation reusable.
purchased = checkout['purchased'].to_numpy()
version = checkout['version'].to_numpy()
def conversion_gap(labels):
"Conversion rate of B minus conversion rate of A, for a given array of labels."
return purchased[labels == 'B'].mean() - purchased[labels == 'A'].mean()
observed_gap = conversion_gap(version)
print('Observed gap (B minus A):', round(observed_gap * 100, 1), 'percentage points')
Observed gap (B minus A): 2.0 percentage points
Applied to the real labels, the function returns the 2.0 percentage points found above. The same function accepts any array of labels, so it can compute the statistic for other labelings.
10.1.4. Shuffling the Labels#
A permutation test builds the null distribution by rearranging the group labels while the outcomes stay where they are. If the version really has no effect, each visitor’s purchase decision would be the same under any arrangement of the labels, so every rearrangement is as plausible as the one that happened.
10.1.4.1. One Shuffle#
rng.permutation returns a randomly reordered copy of an array. Shuffling the version column gives each visitor a new label, but each visitor keeps their own purchase outcome.
rng = np.random.default_rng(10)
shuffled_version = rng.permutation(version)
shuffled = checkout[['visitor_id', 'version', 'purchased']].copy()
shuffled['shuffled_version'] = shuffled_version
print(shuffled[['visitor_id', 'version', 'shuffled_version', 'purchased']].head(6))
print()
print(pd.Series(shuffled_version).value_counts().sort_index())
print()
print('Shuffled gap (B minus A):', round(conversion_gap(shuffled_version) * 100, 2), 'percentage points')
visitor_id version shuffled_version purchased
0 V00001 B A 0
1 V00002 B A 0
2 V00003 B B 0
3 V00004 A A 0
4 V00005 B B 1
5 V00006 B B 0
A 5000
B 5000
Name: count, dtype: int64
Shuffled gap (B minus A): 0.24 percentage points
The shuffle changes who is called A or B but keeps 5,000 visitors in each group and keeps the 900 purchases where they were. Under this arrangement the gap is about a quarter of a percentage point, far from the 2.0 observed.
10.1.4.2. Many Shuffles#
One shuffle gives one value of the statistic. Repeating the shuffle 5,000 times shows the range of gaps that chance alone produces when the version has no effect. The loop uses a boolean mask on the shuffled labels, so each repetition takes only a fraction of a millisecond.
rng = np.random.default_rng(1001)
repetitions = 5000
simulated_gaps = np.empty(repetitions)
for i in range(repetitions):
simulated_gaps[i] = conversion_gap(rng.permutation(version))
print('Simulated gaps: mean', round(simulated_gaps.mean() * 100, 3),
'pp, standard deviation', round(simulated_gaps.std() * 100, 3), 'pp')
print('Largest simulated gap:', round(simulated_gaps.max() * 100, 2), 'percentage points')
Simulated gaps: mean 0.004 pp, standard deviation 0.57 pp
Largest simulated gap: 2.24 percentage points
fig, ax = plt.subplots(figsize=(7, 4))
ax.hist(simulated_gaps * 100, bins=30, color='steelblue', edgecolor='white')
ax.axvline(observed_gap * 100, color='crimson', lw=2.5, label='Observed gap (2.0 pp)')
ax.set_xlabel('Conversion gap, B minus A (percentage points)')
ax.set_ylabel('Number of shuffles (out of 5,000)')
ax.set_title('Chance alone almost never produces a 2-point gap')
ax.legend()
plt.show()
The shuffled gaps pile up around zero with a standard deviation of about 0.6 percentage points. The observed gap of 2.0 points sits at the far right edge, beyond nearly every simulated value.
### Exercise: Preserve the Outcomes
# Shuffle the labels without changing the revenue values.
# 1. Shuffle the group column with ex_rng.permutation.
# 2. Add the shuffled labels as a new column called shuffled.
# 3. Print the group sizes under the new labels.
# Print exactly:
# shuffled
# A 2
# B 2
import numpy as np
import pandas as pd
ex_rng = np.random.default_rng(3)
sales = pd.DataFrame({'group': ['A', 'A', 'B', 'B'], 'revenue': [8, 12, 10, 14]})
### Your code starts here.
### Your code ends here.
shuffled
A 2
B 2
10.1.5. The Conversion Result#
The p-value is the chance, under the null hypothesis, of a test statistic at least as favorable to the alternative as the one observed. Because the alternative is “B is higher”, the test counts simulated gaps that are greater than or equal to the observed gap. The code rounds both to six decimals so that floating-point noise cannot hide a tie.
extreme = np.round(simulated_gaps, 6) >= np.round(observed_gap, 6)
print('Simulated gaps at least as large as observed:', extreme.sum(), 'of', repetitions)
print('Simulated tail proportion (p-value estimate):', extreme.mean())
Simulated gaps at least as large as observed: 3 of 5000
Simulated tail proportion (p-value estimate): 0.0006
Only 3 of the 5,000 shuffles reached the observed gap, so the estimated p-value is far below the conventional 0.05 cutoff (see Hypotheses and p-Values). The result is statistically significant at the 5% level, so reject the null hypothesis: If the checkout version had no effect, a gap this large would almost never arise from the assignment alone. The data favor the alternative: version B converts more visitors. In other words, the data are strong evidence against the null hypothesis.
Reporting a tiny or zero tail. A simulated tail proportion comes from a finite number of shuffles. If none of the 5,000 had reached the observed value, the simulated tail would be zero, but that would not mean the true probability is zero, and it would not establish an exact bound of 1 in 5,000 either. A finite simulation can miss rare outcomes. Report the count of extreme results and the number of repetitions (“3 of 5,000” or “0 of 5,000”), say the p-value is “very small” or “below about 0.001”, and run more repetitions when finer precision matters.
From evidence to a causal reading. Visitors were randomly assigned, so the two groups should differ only by chance in everything other than the page. Time of day, device, and shopping habits are spread across both groups. When the null is rejected, the most plausible explanation is that version B itself raised conversion. This is why randomization supports a causal reading, which Causality develops. The same test on groups that formed without randomization, as in Comparing Groups Without Random Assignment, supports only an association.
Statistical evidence is not the same as practical importance (see Hypotheses and p-Values). Here the gain of 2 buyers per 100 visitors is also large enough to matter to a store, but whether to adopt B depends on its cost and on how much each extra buyer is worth. Order value, which you test next, is part of that.
### Exercise: Choose the Tail
# The statistic is mean B minus mean A. The alternative says B is lower.
# 1. Compute the simulated tail fraction for this alternative.
# Include simulated results equal to the observed value.
# 2. Print it rounded to 3 decimals.
# Print exactly:
# Left-tail fraction: 0.333
import numpy as np
observed = -2.0
simulated = np.array([-3.0, -2.0, -1.0, 0.0, 2.0, 3.0])
### Your code starts here.
### Your code ends here.
Left-tail fraction: 0.333
10.1.6. Order Value: A Second Test#
Conversion counts buyers. A store also cares how much each buyer spends. Among the 900 visitors who bought, you can compare mean order value between versions. The mean of one group minus the mean of the other is a difference in means, and here the statistic is B’s mean minus A’s.
buyers = checkout[checkout['purchased'] == 1]
order_summary = buyers.groupby('version')['order_value'].agg(['count', 'mean', 'std']).round(2)
print(order_summary)
buyer_value = buyers['order_value'].to_numpy()
buyer_version = buyers['version'].to_numpy()
def value_gap(labels):
"Mean order value of B minus mean order value of A, among purchasers."
return buyer_value[labels == 'B'].mean() - buyer_value[labels == 'A'].mean()
observed_value_gap = value_gap(buyer_version)
print('Observed gap (B minus A): $', round(observed_value_gap, 2))
count mean std
version
A 400 63.34 27.56
B 500 65.42 28.94
Observed gap (B minus A): $ 2.08
Purchasers using B spent about $2 more per order on average. The null hypothesis is that the version has no effect on order value, and the alternative is that B raises it. The statistic is the difference in mean order value, B minus A. The method is the same: shuffle the version labels among the 900 purchasers, which keeps 400 labeled A and 500 labeled B, and recompute.
rng = np.random.default_rng(2024)
simulated_value_gaps = np.empty(repetitions)
for i in range(repetitions):
simulated_value_gaps[i] = value_gap(rng.permutation(buyer_version))
value_p = np.mean(simulated_value_gaps >= observed_value_gap)
print('Simulated tail proportion (p-value estimate):', value_p)
fig, ax = plt.subplots(figsize=(7, 4))
ax.hist(simulated_value_gaps, bins=30, color='steelblue', edgecolor='white')
ax.axvline(observed_value_gap, color='crimson', lw=2.5, label='Observed gap')
ax.set_xlabel('Difference in mean order value, B minus A ($)')
ax.set_ylabel('Number of shuffles (out of 5,000)')
ax.set_title('A gap of about $2 in order value is common under chance')
ax.legend()
plt.show()
Simulated tail proportion (p-value estimate): 0.1332
The observed gap sits well inside the simulated distribution: about 13% of shuffles produce a gap this large or larger, so there is little evidence that B raises order value. A $2 difference could easily come from which buyers landed in which group, because individual orders vary by tens of dollars. This does not prove B has no effect on order value, only that these data do not show one.
The business reading is that B brings more buyers, not bigger baskets. The two results together describe where B’s gain comes from. To see its total effect on revenue, combine them in one measure. Revenue per visitor is total revenue divided by all visitors, with non-buyers counted as $0. It equals the conversion rate times the mean order value among buyers.
checkout['revenue'] = checkout['order_value'].fillna(0)
rev = checkout.groupby('version')['revenue'].mean().round(2)
print(rev)
print('Revenue per visitor, B minus A: $', round(rev['B'] - rev['A'], 2))
version
A 5.07
B 6.54
Name: revenue, dtype: float64
Revenue per visitor, B minus A: $ 1.47
Each visitor shown B brought in about $1.47 more than each visitor shown A, almost all of it from the extra buyers. Over 100,000 visitors that would be roughly $147,000, before the cost of building and maintaining the new page.
### Exercise: Revenue per Visitor
# Revenue per visitor counts visitors who did not buy as $0.
# 1. Load checkout_test.csv and make a revenue column: order_value with blanks filled by 0.
# 2. Compute revenue per visitor for A and for B (the mean of revenue by version).
# 3. Print both, rounded to 2 decimals, and the difference B minus A.
# Print exactly:
# A: 5.07
# B: 6.54
# B minus A: 1.47
import pandas as pd
ex_path_data = '../../data/'
checkout_ex = pd.read_csv(ex_path_data + 'checkout_test.csv')
### Your code starts here.
### Your code ends here.
A: 5.07
B: 6.54
B minus A: 1.47
10.1.7. Section Practice#
Use the permutation test on a small A/B test of order value. The exercise is self-contained. groupby also accepts an array of labels in place of a column name. Each value in the array is the group label for the row in the same position, so df.groupby(labels)['value'].mean() averages value within each label. This lets you regroup the same rows under shuffled labels without changing the DataFrame.
### Exercise: Practice A/B Testing
# An online store showed two checkout pages, A and B, at random.
# 1. Compute the observed difference in mean order value: B minus A.
# 2. Shuffle the version labels 5,000 times (ex_rng.permutation) and compute the
# difference each time.
# 3. Compute the p-value: the proportion of shuffled differences at least as large
# as the observed difference. Print the observed difference and the p-value.
# Print exactly:
# Observed difference: 8.0
# P-value: 0.0002
import numpy as np
import pandas as pd
ex_rng = np.random.default_rng(1)
orders = pd.DataFrame({
'version': ['A', 'B'] * 8,
'value': [42, 47, 38, 52, 45, 49, 40, 46, 44, 53, 41, 48, 39, 50, 43, 51],
})
### Your code starts here.
### Your code ends here.
Observed difference: 8.0
P-value: 0.0002