…
…
Statistics and Data Analysis Fundamentals · Lesson 29 / 44 · Inference by simulation
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
From April 15 to 28, Bazaar tested the new design of its mobile checkout page (B) against the old one (A), with visitors split at random into two groups of 500. The purchase rate was 13% in A and 8% in B. The product team says, "The gap is small, and with 1,000 visitors it could be luck." In this lesson you will test that objection by shuffling labels.
Comparing two groups is the most common statistical task in data analysis: new design or old, message A or message B, this month or last month. In lesson 27 you compared one proportion with a claim (a return rate of 5%). In lesson 28 you learned the p-value and the language of decisions. In this lesson you will apply the same logic to the difference between two groups. All you need to know for it is how to shuffle a deck of cards.
At the end of the lesson you will take this chart and this sentence to the product team. The chart shows 10,000 differences you could see if the group labels had no effect on purchases at all:
shuffles · Bazaar sessions.csv with label shuffling, seed 42 (fictional sample data)
The report sentence: "The purchase rate is 5 points lower in design B. If the labels did not matter, a gap this large would appear in only 1.35% of 10,000 shuffles (two-sided p = 0.0135). Because visitors were assigned at random, we can link the drop to the design."
In this lesson you will:
Before you start calculating, test your intuition. All you have is two proportions and the group sizes:
The purchase rate is 13% in group A and 8% in group B, with 500 visitors in each group. Can this 5-point gap be explained by chance?
Before you compare two groups, ask two questions. The first: what are you comparing? A proportion (the share of visitors who bought) or a mean (the average checkout time)? The second: are the groups independent? Does each visitor belong to only one group, and does one person's result not affect anyone in the other group? In Bazaar's test the answers are clear: we compare the purchase rate, and each visitor saw either A or B.
Then we reduce the two groups to one number. This number is called the test statistic. For comparing two groups, the most natural choice is the difference: for proportions, the B proportion − the A proportion; for means, the B mean − the A mean. The sign gives the direction: a negative difference means "B is lower" and a positive difference means "B is higher".
Remember from lesson 7: the mean of a 0/1 column is the share of 1s. The purchased column is 1 for a session with a purchase and 0 for a session without one. So the mean per group gives the purchase rate directly:
import pandas as pd df = pd.read_csv("sessions.csv") rate = df.groupby("group")["purchased"].mean() print(rate) observed = rate["B"] - rate["A"] print("Difference (B - A):", round(observed, 3))
Outputgroup
A 0.13
B 0.08
Name: purchased, dtype: float64
Difference (B - A): -0.05In group A, 65 of 500 visitors bought (0.13). In group B, 40 did (0.08). The difference is −0.05: the purchase rate is 5 points lower with the new design. We call this number the observed difference. The rest of the lesson asks whether this one number can be explained by chance.
Let's set one rule about direction and always follow it: B − A, which means new minus old. If you wrote "A − B" you would get +0.05, and it would carry the same information. But a reader who does not know which was subtracted from which might see "+0.05" and think the new design is better. The direction of the sign matters. Always write in the report which way the difference was taken.
In the cell below, do the same calculation for two other columns from Bazaar. Change the column variable and look at the sign of the difference:
Try it now· not graded; doesn't affect progress
With the new design, more people add the product to the cart (+5 points). The share who reach the checkout page is almost the same (+0.6 points). But the share who buy goes down (−5 points). There are three differences. Which one is real and which one is chance? To answer that, we need a model of chance.
In lesson 27 you wrote the null hypothesis as one number: "the true return rate is 0.05". When you compare two groups, H₀ is this: the group label does not affect the result. At Bazaar, that means the design does not affect purchases at all. Each visitor would make the same decision whether they saw A or B. The alternative (H₁) is that the design changes the purchase rate. The question is "did it change", so H₁ is two-sided. The rule from lesson 28 applies here too: you choose the direction from the question, not from the data.
If H₀ is true, something very useful follows. If each visitor's decision is already fixed, then the group they landed in is only a label. If we redistributed the labels at random, the results would not change. Only the choice of which result counts as "A" and which as "B" would change. So the way to produce the differences you could see under H₀ is clear: shuffle the labels, calculate the difference again, and repeat thousands of times. This method is called the permutation test.
Notice what this comparison shows: the cards, which are the results, never change. Shuffling does not damage the data. 105 purchases stay 105 purchases. The only thing that changes is which card lands in which envelope. Let's follow this step by step with a tiny example of six students. A teacher gives a new study method to three students (B), and three students continue with the old method (A). The list passed shows whether each student passed the exam. In the first round we count passes with the real labels, and in the second round with shuffled labels:
Run the code line by line: see which line runs next, the variable boxes and the output.
group = ["A", "A", "A", "B", "B", "B"] shuffled = ["B", "A", "A", "A", "B", "B"] passed = [1, 1, 0, 0, 1, 0] for labels in [group, shuffled]: passed_A = 0 passed_B = 0 for i in range(6): if labels[i] == "A": passed_A = passed_A + passed[i] else: passed_B = passed_B + passed[i] diff = passed_B / 3 - passed_A / 3 print("A:", passed_A, "| B:", passed_B, "| total:", passed_A + passed_B, "| difference:", round(diff, 2))
With the real labels, 2 students passed in A and 1 in B: the difference is 1/3 − 2/3 = −0.33. With the shuffled labels, 1 passed in A and 2 in B: the difference is +0.33. In both rounds the total of passes is 3. The passed list never changed. Shuffling makes this idea concrete: "if the method did not matter, the same three successes could have landed in the groups in a different way."
You can shuffle six cards by hand. Shuffling 1,000 cards 10,000 times is a job for the computer. The permutation method of the NumPy generator puts the elements of an array in a random order: the same elements, a new order. In lesson 25 you used rng.choice to select; permutation adds nothing and removes nothing. It only moves things around. For speed, we convert the columns to NumPy arrays with to_numpy() (lesson 14). The filtering you learned in pandas works the same way on a NumPy array: outcome[shuffled == "B"] gives the results where the label is B.
import numpy as np import pandas as pd df = pd.read_csv("sessions.csv") group = df["group"].to_numpy() outcome = df["purchased"].to_numpy() rng = np.random.default_rng(42) shuffled = rng.permutation(group) print("Real labels: ", group[:10]) print("Shuffled labels:", shuffled[:10]) print("B count:", (shuffled == "B").sum(), "| total purchases:", outcome.sum()) diff = outcome[shuffled == "B"].mean() - outcome[shuffled == "A"].mean() print("Difference in this shuffle:", round(diff, 3))
OutputReal labels: ['A' 'A' 'B' 'A' 'B' 'B' 'A' 'A' 'B' 'A']
Shuffled labels: ['B' 'A' 'B' 'B' 'B' 'B' 'A' 'B' 'B' 'A']
B count: 500 | total purchases: 105
Difference in this shuffle: 0.046The labels of the first ten visitors changed. But the number of visitors labeled B is still 500, and the total number of purchases is still 105. In this one shuffle the difference came out +0.046. Even if the labels did not matter, B could look 4.6 points higher than A. One shuffle proves nothing. You need thousands of repeats, as in lesson 27. Before building the loop, get the order of the lines clear in your head:
Put the lines of the permutation test in the correct order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Now the full loop. In each round we shuffle the labels and add the difference to a list. After 10,000 rounds we have a list of 10,000 differences. This list is the distribution of differences you could see if H₀ were true. It is the null distribution of this test:
import numpy as np import pandas as pd df = pd.read_csv("sessions.csv") group = df["group"].to_numpy() outcome = df["purchased"].to_numpy() observed = outcome[group == "B"].mean() - outcome[group == "A"].mean() rng = np.random.default_rng(42) diffs = [] for i in range(10_000): shuffled = rng.permutation(group) diff = outcome[shuffled == "B"].mean() - outcome[shuffled == "A"].mean() diffs.append(diff) diffs = np.array(diffs) print("Mean:", round(diffs.mean(), 4), "| standard deviation:", round(diffs.std(), 4)) print("Middle 95%:", np.percentile(diffs, [2.5, 97.5])) print("Smallest:", round(diffs.min(), 3), "| largest:", round(diffs.max(), 3))
OutputMean: 0.0 | standard deviation: 0.0196
Middle 95%: [-0.038 0.038]
Smallest: -0.102 | largest: 0.07This is the ID card of the null distribution. Its center is 0 (if the labels do not matter, the expected difference is zero), and its standard deviation is about 0.02. The middle 95% of the 10,000 shuffles lies between −0.038 and +0.038. So even if the labels did not matter, differences of 3 to 4 points between the two groups would be ordinary. But the observed −0.05 falls outside this range. The most extreme shuffle went down to −0.102, so chance can produce a 5-point gap. The real question is: how often?
In lesson 28 you defined the p-value: the probability of seeing a result at least as extreme as the observed one if H₀ were true. What does "more extreme" mean here? The question is "did the design change purchases", so both directions count: differences of −0.05 or lower, and differences of +0.05 or higher. The two-sided p is the share of differences whose absolute value is greater than or equal to the absolute value of the observed difference: (np.abs(diffs) >= abs(observed)).mean().
import numpy as np import pandas as pd df = pd.read_csv("sessions.csv") group = df["group"].to_numpy() outcome = df["purchased"].to_numpy() observed = outcome[group == "B"].mean() - outcome[group == "A"].mean() rng = np.random.default_rng(42) diffs = [] for i in range(10_000): shuffled = rng.permutation(group) diffs.append(outcome[shuffled == "B"].mean() - outcome[shuffled == "A"].mean()) diffs = np.array(diffs) two_sided = (np.abs(diffs) >= abs(observed)).mean() one_sided = (diffs <= observed).mean() print("Observed difference:", round(observed, 3)) print("Two-sided p:", two_sided) print("One-sided p (B lower):", one_sided)
OutputObserved difference: -0.05
Two-sided p: 0.0135
One-sided p (B lower): 0.0064In 135 of the 10,000 shuffles, the difference was at least 0.05 in absolute value: two-sided p = 0.0135. Compare this with the significance level α = 0.05, which you chose in advance. Since p < α, H₀ is rejected. If the labels really did not matter, a difference this large would appear only about once in a hundred tries. The one-sided p (only the "B is lower" direction) is 0.0064. But we set up the question as two-sided from the start. Switching to one-sided after seeing the data would cut p in half artificially (lesson 28).
Now run the full test yourself. The cell draws a histogram and puts two red lines on it: one at the observed difference and one at its mirror image (+0.05). The bars outside the two lines make up p:
Try it now· not graded; doesn't affect progress
When you change the number of shuffles, the third decimal of p moves (0.015, 0.0124, 0.0135). But all three are far below 0.05, and the decision stays the same. As you saw in lesson 27, when p is not very close to the threshold, the randomness of the simulation does not change the decision.
Now we reach the most instructive result of this lesson. The add-to-cart difference is also exactly 5 points, but in the opposite direction (+0.05). Let's apply the same test to the added_to_cart column:
import numpy as np import pandas as pd df = pd.read_csv("sessions.csv") group = df["group"].to_numpy() outcome = df["added_to_cart"].to_numpy() observed = outcome[group == "B"].mean() - outcome[group == "A"].mean() rng = np.random.default_rng(42) diffs = [] for i in range(10_000): shuffled = rng.permutation(group) diffs.append(outcome[shuffled == "B"].mean() - outcome[shuffled == "A"].mean()) diffs = np.array(diffs) print("Add-to-cart rates: A", outcome[group == "A"].mean(), "| B", outcome[group == "B"].mean()) print("Observed difference:", round(observed, 3)) print("Standard deviation of the null distribution:", round(diffs.std(), 4)) print("Middle 95%:", np.percentile(diffs, [2.5, 97.5])) print("Two-sided p:", (np.abs(diffs) >= abs(observed)).mean())
OutputAdd-to-cart rates: A 0.31 | B 0.36
Observed difference: 0.05
Standard deviation of the null distribution: 0.0298
Middle 95%: [-0.058 0.058]
Two-sided p: 0.1058The same 5 points, but p = 0.106. At α = 0.05, H₀ cannot be rejected. Why? This time the null distribution is wider: its standard deviation is 0.0298, not 0.0196, and its middle 95% is ±0.058, not ±0.038. The purchase rate was around 10%. The add-to-cart rate is around 30–36%. The spread of a 0/1 result grows as the proportion gets closer to 0.5 (the variance of a proportion is p(1 − p), the idea of spread from lesson 14). When more "yes" and "no" results are mixed, the shuffles produce larger differences too, and 5 points stays ordinary at this width.
The lesson here: the difference by itself does not decide. Its place in the null distribution decides. Saying "5 points is a large gap" or "5 points is a small gap" tells you nothing on its own. One more warning: p = 0.106 does not mean "the two groups are the same for add-to-cart". As in lesson 28: the evidence is not enough, the difference could not be shown. The true difference could be zero, or it could be 5 points.
The second thing that sets the width of the null distribution is the sample size. In the tiny experiment below, a teacher tries two study methods with 12 + 12 students. In group A, 9 students passed, and this stays fixed. Change the number who passed in B and watch how p changes:
In an experiment with 12 + 12 students, 9 students passed in A. How do the difference and the two-sided p change as the number who passed in B changes? (2,000 shuffles, seed 42)
Pick a value; predict the output first, then look.
1import numpy as np2passed_B = 33group = np.array(["A"] * 12 + ["B"] * 12)4outcome = np.array([1] * 9 + [0] * 3 + [1] * passed_B + [0] * (12 - passed_B))5observed = outcome[group == "B"].mean() - outcome[group == "A"].mean()6rng = np.random.default_rng(42)7diffs = []8for i in range(2_000):9 shuffled = rng.permutation(group)10 diffs.append(outcome[shuffled == "B"].mean() - outcome[shuffled == "A"].mean())11p = (np.abs(np.array(diffs)) >= abs(observed)).mean()12print("A: 9 / 12 passed | B:", passed_B, "/ 12 passed")13print("Difference (B - A):", round(observed, 2), "| two-sided p:", p)
A: 9 / 12 passed | B: 3 / 12 passed Difference (B - A): -0.5 | two-sided p: 0.046
Faded lines didn't run with this value. With groups of 12, the null distribution is very wide. Even a 33-point difference (9 / 12 against 5 / 12) appears in one fifth of the shuffles. Only the 50-point difference stays borderline, with p = 0.046. At Bazaar, 5 points was significant because each group had 500 visitors.
In groups of 12 students, a 33-point difference is easily explained by chance. At Bazaar, with groups of 500, a 5-point difference could not be explained. The base rate and the sample size set the width of the null distribution. The p-value measures how far out the observed difference lies compared with that width.
In the purchase test, H₀ was rejected. Now comes the most important question: can this result be read as "the new design reduced purchases"? Remember the distinction from lesson 3: in an experiment, the researcher assigns the groups at random. In an observation, the groups form on their own. In Bazaar's test, visitors landed in A or B at random. Random assignment makes the two groups similar, on average, in everything except the design: age, device, shopping habits, even the mood of the day. The only systematic difference left is the design. So the decision "H₀ is rejected" can be read here as "the design created the difference".
Now let's apply the same method to observational data. At Bazaar, the return rate for mobile orders is 0.0795 and for desktop orders 0.0623 (a difference of +0.0171; you will calculate it in the examples and exercises below). Here nobody assigned customers to devices at random. Customers chose their device themselves. Mobile users may be younger, may buy from other categories, or may have arrived through a campaign link. The permutation test tells you whether this difference can be explained by chance. But even if the result is significant, you cannot write "the mobile app causes returns". The only thing you can write is: "there is a difference, and its cause cannot be told from this data."
This is the common misunderstanding: a significant difference does not always mean cause and effect. Significance says "not chance". It does not say "because of this". What allows you to use the language of cause is not the p-value but the way the data was collected. You fix the product manager's report:
The product manager will write the result of the permutation test (purchase difference −0.05, two-sided p = 0.0135) for senior management in one sentence. Which sentence should they choose?
Pick an option and see what happens. There are no points; you can try the other options too.
The permutation test works not only for proportions but also for means. The only line that changes is the line that calculates the difference: the mean of the measured value instead of the mean of a 0/1 column. In Bazaar's data, the checkout time in seconds exists for sessions that reached the checkout page (it is empty for the others). Does checkout take longer with the new design? Let's drop the missing values and set up the same test:
import numpy as np import pandas as pd df = pd.read_csv("sessions.csv") sub = df.dropna(subset=["checkout_time_sec"]) print("Sessions that reached checkout:", len(sub)) print(sub.groupby("group")["checkout_time_sec"].mean().round(1)) group = sub["group"].to_numpy() seconds = sub["checkout_time_sec"].to_numpy() observed = seconds[group == "B"].mean() - seconds[group == "A"].mean() rng = np.random.default_rng(42) diffs = [] for i in range(10_000): shuffled = rng.permutation(group) diffs.append(seconds[shuffled == "B"].mean() - seconds[shuffled == "A"].mean()) diffs = np.array(diffs) print("Observed difference (sec):", round(observed, 1)) print("Most extreme shuffle difference (sec):", round(np.abs(diffs).max(), 1)) print("Number of shuffles this extreme:", (np.abs(diffs) >= abs(observed)).sum())
OutputSessions that reached checkout: 195
group
A 98.7
B 133.4
Name: checkout_time_sec, dtype: float64
Observed difference (sec): 34.7
Most extreme shuffle difference (sec): 20.5
Number of shuffles this extreme: 0Across 195 sessions, checkout takes 34.7 seconds longer on average in B. The most extreme of the 10,000 shuffles produced a difference of only 20.5 seconds. Not even one shuffle came close to 34.7. So how do we write p?
In none of the 10,000 shuffles was the checkout time difference as extreme as the observed 34.7 seconds. Which is the best sentence for p?
In the report you write "p < 0.0001 (never seen in 10,000 shuffles)". Because visitors were assigned at random, we can say the new design made checkout longer. This may also be one possible explanation for the drop in purchases. That last sentence is a hypothesis, not a tested result. In lesson 42, when we build the whole A/B test, we will return to this question.
The same difference calculation works on observational data, but the interpretation changes. First, let's write the two proportions and the difference (you will build the test in a5):
import pandas as pd s = pd.read_csv("orders.csv") s["returned"] = s["status"] == "returned" rate = s.groupby("device")["returned"].mean() print(rate.round(4)) print("Difference (mobile - desktop):", round(rate["mobile"] - rate["desktop"], 4))
Outputdevice
desktop 0.0623
mobile 0.0795
Name: returned, dtype: float64
Difference (mobile - desktop): 0.0171The return rate is 1.7 points higher on mobile. Whatever the result of the test, the end of the sentence stays the same: customers chose their devices themselves, so the difference cannot be linked to the device.
Let's shuffle the six-student experiment from the explanation 10,000 times. What happens with very small groups?
import numpy as np group = np.array(["A", "A", "A", "B", "B", "B"]) passed = np.array([1, 1, 0, 0, 1, 0]) observed = passed[group == ].mean() - passed[group == ].mean() rng = np.random.default_rng(42) diffs = [] i (10_000): shuffled = rng.permutation(group) diffs.(passed[shuffled == ].mean() - passed[shuffled == ].mean()) diffs = np.array(diffs) (, (observed, 2)) (, np.unique(np.(diffs, 2))) (, (np.(diffs) >= (observed)).mean())
Shuffling the rows instead of the labels. df.sample(frac=1) shuffles the whole table: each row moves together with its label and its result. Because which result belongs to which label never changes, every "shuffle" gives the same difference as the observed one:
import numpy as np import pandas as pd df = pd.read_csv("sessions.csv") observed = df.groupby("group")["purchased"].mean() observed = observed["B"] - observed["A"] diffs = [] for i in range(1_000): shuffled = df.sample(frac=1, random_state=i) rate = shuffled.groupby("group")["purchased"].mean() diffs.append(rate["B"] - rate["A"]) diffs = np.array(diffs) print("Number of distinct difference values:", len(np.unique(np.round(diffs, 6)))) print("Two-sided p:", (np.abs(diffs) >= abs(observed)).mean())
OutputNumber of distinct difference values: 1
Two-sided p: 1.0All 1,000 shuffles gave the same difference (−0.05), and p came out as 1. The code gives no error, so the mistake goes unnoticed, and an analyst may reach the opposite conclusion, "p = 1, the two designs are the same". The correct way is to shuffle only the label column:
rng.permutation(group). The list of differences is the null distribution, and the two-sided p is counted with (np.abs(diffs) >= abs(observed)).mean() (at Bazaar, 0.0135 for purchases and 0.106 for add-to-cart with a difference of the same size).Next lesson: You said "B is 5 points lower", but the true drop could be 1 point or 9 points. You will learn to give the size of a difference as an interval using the bootstrap.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
| — | number of shuffles |
|---|---|
| −0.12 / −0.10 | 1 |
| −0.10 / −0.08 | 1 |
| −0.08 / −0.06 | 8 |
| −0.06 / −0.04 | 198 |
| −0.04 / −0.02 | 1286 |
| −0.02 / 0 | 3497 |
| 0 / 0.02 | 3446 |
| 0.02 / 0.04 | 1354 |
| 0.04 / 0.06 | 198 |
| 0.06 / 0.08 | 11 |
OutputObserved difference: -0.33
Differences seen: [-1. -0.33 0.33 1. ]
Two-sided p: 1.0When three successes are spread across six people, only four differences are possible: −1, −0.33, +0.33, +1. Every shuffle produces a gap of at least 33 points, so p = 1. With six people, no method can show a difference. When the sample is very small, a large p does not mean "there is no difference". It means "this data cannot tell".
rng.permutation(group)