…
…
Statistics and Data Analysis Fundamentals · Lesson 43 / 44 · A/B tests and fallacies
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.
Before the board meeting, six sentences have entered Bazaar's draft report. The calculation behind every sentence is correct, but each one says more than the data can support. You will correct the report before the meeting.
This lesson is a workshop. It has almost no new pandas tools. Instead, it turns the tools from earlier lessons (merging, grouping, p-values, rates, confounders) into a checklist. Until now you mostly asked, "How do I do the calculation correctly?" In this lesson the question changes: how can a result be wrong when the calculation is right? In real work, this is the kind of mistake that damages analyses most. A code error gives you an error message. A thinking error gives no warning at all: it goes into the report, and in the meeting it becomes a decision.
The six sentences from the draft report are below. By the end of the lesson you will be able to name the flaw in each one and correct it like the right-hand column. For now, read the right-hand column only as a goal. We will open each row in its own section, together with the data.
| # | Draft sentence | Flaw | Corrected sentence |
|---|---|---|---|
| F1 | "Our customers' satisfaction is 3.93 / 5: customers are happy." | Selection bias | "Customers whose orders were completed rate satisfaction at 3.93; customers who returned or canceled are not in the survey." |
| F2 | "Orders collapsed by 41%." | Cherry-picking | "June's 104 orders are 38% below the January–April monthly average (167)." |
| F3 | "The day after the 10 busiest days, orders drop by half; those days have a stock problem." | Regression to the mean | "The day after a record day returns to the usual level (5.6; all days 5.5); there is no evidence of a stock problem." |
| F4 | "We looked at 18 carrier × month cells: Caravan Freight's February returns are significantly higher (p = 0.035)." | Multiple comparisons | "One of 18 tests is below 0.05; at the Bonferroni threshold of 0.0028 none is significant. The finding is a discovery and must be tested on new data." |
| F5 | "The new checkout page lowered purchases by only 5%." | Percent vs. percentage points | "The purchase rate fell from 13% to 8%: 5 points, a relative drop of 38.5%." |
| F6 |
There is one question that works against all six flaws: "What else could explain this number?" If you ask it before you write a sentence, you will catch most of the mistakes below on your own.
Why does it matter? An average describes only the people you measured. If the people you measured are systematically different from all customers, the average says something wrong about all customers, however correctly it is calculated. In lesson 3 you saw this as the convenience sample and the voluntary response: who gets into the sample pushes the result in one direction from the start. When getting into the sample passes through a filter that is related to the result, it is called selection bias.
Bazaar's survey went to 300 customers. To see who it went to, let's connect the survey to the orders table with the merge from lesson 9 and count the status of each answer's order:
import pandas as pd survey = pd.read_csv("survey.csv") orders = pd.read_csv("orders.csv") print("Survey responses:", len(survey), "| mean satisfaction:", survey["satisfaction"].mean()) merged = survey.merge(orders[["order_id", "status"]], on="order_id") print(merged["status"].value_counts()) print(orders["status"].value_counts())
OutputSurvey responses: 300 | mean satisfaction: 3.93
status
completed 300
Name: count, dtype: int64
status
completed 787
returned 64
canceled 34
Name: count, dtype: int64All 300 answers come from completed orders. But of Bazaar's 885 orders, 64 were returned and 34 were canceled: about one order in nine never had a chance to enter the survey. The survey was not sent to customers who returned or canceled. These customers probably had a worse experience, because they sent the product back or gave up on the order. The number 3.93 is correct as a calculation, but the sentence "customers are happy" also covers the customers who could not enter the survey.
The correction takes one of two routes. You can fit the sentence to the data ("customers whose orders were completed rate satisfaction at 3.93"), or you can fit the data to the question (send the survey to customers who returned or canceled as well). Both are honest. What is wrong is spreading the number of a narrow group to a wider group. Try it yourself:
Try it now· not graded; doesn't affect progress
The last line says that 88.9% of orders were completed, 7.2% were returned, and 3.8% were canceled. The 11% who could not enter the survey may be pulling the result up. We cannot know by how much with this data, because those customers have no answers. You also write down that you cannot know.
If the survey had also been sent to customers who returned or canceled, what would the mean satisfaction most likely have done?
Why does it matter? Every sentence about a change has two ends: a start and an end. The freedom to choose one of the ends is enough to produce very different headlines from the same data. Choosing the start and end points to fit the story you want is called cherry-picking: it is like picking only the ripest cherries from a tree and saying "all the cherries are like this."
Let's see where the draft's "collapsed by 41%" comes from. Below are the monthly order counts (all orders, including returned and canceled) and the change of the same June against three different starting points:
import pandas as pd orders = pd.read_csv("orders.csv") orders["month"] = pd.to_datetime(orders["date"]).dt.month monthly = orders.groupby("month").size() print(monthly) june = monthly[6] print("From February:", round((june / monthly[2] - 1) * 100, 1)) print("From January:", round((june / monthly[1] - 1) * 100, 1)) print("From the Jan-Apr average:", round((june / monthly.loc[1:4].mean() - 1) * 100, 1))
Outputmonth
1 154
2 177
3 176
4 162
5 112
6 104
dtype: int64
From February: -41.2
From January: -32.5
From the Jan-Apr average: -37.8The same June, the same data, three headlines: 41%, 32.5%, and 38%. The draft says "41%" because it started from February, and February is the best of the six months (177). Any comparison that starts at the highest point makes the drop look larger, and any comparison that starts at the lowest point makes a rise look larger. Which one is right? The answer to this question is not in the number but in the reason. At Bazaar, May 1 is a break date (the ads were cut and the new checkout page opened). So the honest comparison is between "the whole period before the break" and "the period after": the January–April monthly average is 167, June is 104, and the drop is 38%. Starting from January also rests on a single month and depends on the luck of that month.
The rule is: the comparison period is chosen before you look at the result, and with a reason. The report also states the reason ("against the average of the four months before the break date"). Change the start and see how the headline changes:
Change the start of the comparison: which headline does the same June produce?
Pick a value; predict the output first, then look.
1monthly = {"January": 154, "February": 177, "March": 176, "April": 162, "May": 112, "June": 104}2start = "February"3if start == "Jan-Apr average":4 before = (monthly["January"] + monthly["February"] + monthly["March"] + monthly["April"]) / 45else:6 before = monthly[start]7change = (monthly["June"] / before - 1) * 1008print("Start:", start, "=", before)9print("Change:", round(change, 1), "%")10if change <= -40:11 print("Headline: Orders collapsed!")12elif change <= -35:13 print("Headline: Orders fell sharply")14else:15 print("Headline: Orders fell by a third")
Start: February = 177 Change: -41.2 % Headline: Orders collapsed!
Faded lines didn't run with this value. From February: −41.2. From January: −32.5. From the Jan–Apr average: −37.8. All three headlines are arithmetically correct. Which one goes into the report is decided not by the number but by a reason written in advance. The whole period before the break date does not depend on the luck of a single month.
Cherry-picking also has an end point: for example, ending a campaign's evaluation at its best week. As an example outside the case, think of the price of a stock (fictional sample data): 100, 92, 75, 60, 70, 84, 96. The sentence "up 60% from the lowest point" is true, and so is "down 4% since the start of the period." Which one becomes the headline in the news shows the story the writer wants to tell.
Why does it matter? If you choose a group by its extreme values (the best days, the weakest students, the junctions with the most accidents), that group moves toward the average by itself in the next measurement. If you do not notice this, you invent a cause although nothing happened ("a stock problem", "the extra lessons worked"). In lesson 38 you saw the name of this effect in a box: regression to the mean. Here we explain its cause and how to recognize it.
Think of a day's order count as the sum of two parts: the usual level of that period, and the luck specific to that day (who happened to visit the site, who got paid, what the weather was like). When you choose the top 10 days, you have not chosen the days with a high usual level. You have mostly chosen the days with high luck. The next day, the usual level is the same, but luck is drawn again, and on average it returns to zero. The result: the next day is close to a usual day.
First follow this with a small list of 12 days, step by step. The code counts days with 8 or more orders as "high days" and collects the day after each of them. Watch how the high and next_days lists fill up in the variable boxes:
Run the code line by line: see which line runs next, the variable boxes and the output.
daily_orders = [5, 9, 4, 6, 3, 10, 5, 6, 8, 7, 5, 4] average = sum(daily_orders) / len(daily_orders) high = [] next_days = [] for i in range(len(daily_orders) - 1): if daily_orders[i] >= 8: high.append(daily_orders[i]) next_days.append(daily_orders[i + 1]) print("All days:", average) print("High days:", high, "average", sum(high) / len(high)) print("Next days:", next_days, "average", round(sum(next_days) / len(next_days), 2))
The average of the high days is 9, the average of the next days is 5.33, and the average of all days is 6. The next days seem to have "dropped by almost half," but in fact they went back to ordinary days, even slightly below. The loop goes up to len(daily_orders) - 1 because the day after the last day is not in the list.
Now let's look at Bazaar's real days. We take the January–April period, when the ads were running (so that the break in May does not spoil the comparison). With the shift you saw in lesson 41, we put the next day's orders beside each day; shift(-1) moves the column up by one row. The day after the last day is not in this period, so we drop that row. nlargest and nsmallest from lesson 5 give the 10 largest and 10 smallest rows:
import pandas as pd marketing = pd.read_csv("marketing.csv") days = marketing[marketing["date"] < "2026-05-01"].copy() days["next_day"] = days["orders"].shift(-1) days = days.dropna(subset=["next_day"]) top = days.nlargest(10, "orders") bottom = days.nsmallest(10, "orders") print("Days:", len(days), "| average of all days:", round(days["orders"].mean(), 2)) print("Top 10 days:", top["orders"].mean(), "| next days:", top["next_day"].mean()) print("Bottom 10 days:", bottom["orders"].mean(), "| next days:", bottom["next_day"].mean())
OutputDays: 119 | average of all days: 5.51
Top 10 days: 10.6 | next days: 5.6
Bottom 10 days: 1.7 | next days: 6.2The top 10 days average 10.6 orders; the next days average 5.6. The draft read this as "drops by half, there is a stock problem." But the average of all days is 5.51: the next days are exactly as good as an ordinary day. The last line is the mirror image of the same effect: the day after the 10 worst days "jumps" from 1.7 to 6.2. With the draft's logic, we could also read this as "customers make up for it after bad days." Both stories come from the same fallacy.
The way to recognize regression to the mean is to ask: did I choose the group by its extreme value? If you did, expect the next measurement to move toward the average, and count this expectation in before you look for a cause. To measure the effect of an intervention (extra lessons, a new traffic light), you also need a control group that was chosen in the same way but did not receive the intervention. We will build one in section 7.
In a class, the 10 students with the highest scores on the first exam take a second exam of similar difficulty. What do they do on average?
Why does it matter? In lesson 33 you saw the second meaning of α: the chance that a test comes out "significant" when there is no real difference. α = 0.05 is a reasonable false-alarm rate for a single test. But if you run many tests on one dataset, each carries a 5% false-alarm risk, and these risks add up. With no effect at all, it becomes almost certain that one of a few tests comes out "significant." Trying tests one by one and reporting the one that is significant is called p-hacking.
Let's build the draft's sentence from the data. The analyst compared the return rate of each of the 3 carriers × 6 months = 18 cells with the rest of the orders, using the proportions_ztest from lesson 31:
import pandas as pd from statsmodels.stats.proportion import proportions_ztest orders = pd.read_csv("orders.csv") orders["month"] = pd.to_datetime(orders["date"]).dt.month orders["returned"] = orders["status"] == "returned" results = [] for (carrier, month), cell in orders.groupby(["carrier", "month"]): rest = orders.drop(cell.index) z, p = proportions_ztest([cell["returned"].sum(), rest["returned"].sum()], [len(cell), len(rest)]) results.append({"carrier": carrier, "month": month, "orders": len(cell), "return_rate": round(cell["returned"].mean(), 3), "p": round(p, 4)}) table = pd.DataFrame(results).sort_values("p") print("Number of tests:", len(table)) print(table.head(3)) print("p < 0.05:", (table["p"] < 0.05).sum()) (, (0.05 / (table), 4), , (table[] < 0.05 / (table)).())
OutputNumber of tests: 18
carrier month orders return_rate p
7 Caravan Freight 2 56 0.143 0.0352
14 Gull Post 3 65 0.031 0.1791
2 Arrow Express 3 73 0.110 0.1993
p < 0.05: 1
Bonferroni threshold: 0.0028 | below it: 0One of the 18 tests is below 0.05: Caravan Freight, February, return rate 14.3%, p = 0.035. The draft wrote this as a finding. But the real question is: if there were no real difference in any cell, how likely is it that at least one of 18 tests falls below 0.05?
Let's see it with a simulation. Remember the A/A test from lesson 33: the true rates of the two groups are the same (10%), with 500 people in each group. This time one "analysis" consists of 20 A/A tests, and we run 10,000 analyses. The code is the same function as in lesson 33; the only difference is that size=(reps, m) produces m tests in each row. (p < 0.05).any(axis=1) tells us, for each row (each analysis), whether at least one test came out significant:
import numpy as np from scipy import stats def aa_tests(m, n=500, rate=0.10, reps=10_000): rng = np.random.default_rng(42) xa = rng.binomial(n, rate, size=(reps, m)) xb = rng.binomial(n, rate, size=(reps, m)) pooled = (xa + xb) / (2 * n) se = np.sqrt(pooled * (1 - pooled) * 2 / n) z = (xa - xb) / n / se return 2 * stats.norm.sf(np.abs(z)) p = aa_tests(20) print("Share significant in a single test:", round((p < 0.05).mean(), 3)) print("At least one of 20 tests significant:", (p < 0.05).any(axis=1).mean()) print("Formula 1 - 0.95**20:", round(1 - 0.95**20, 3)) print("With Bonferroni (0.05 / 20):", (p < 0.05 / 20).any(axis=1).mean())
OutputShare significant in a single test: 0.049
At least one of 20 tests significant: 0.6347
Formula 1 - 0.95**20: 0.642
With Bonferroni (0.05 / 20): 0.0448Looked at one by one, each test gives about 5% false alarms, exactly as expected. But in 63.5% of the 20-test analyses, at least one test comes out "significant," although there is no real difference anywhere. The formula says the same thing: the chance that one test does not give a false alarm is 0.95; the chance that none of 20 independent tests gives one is 0.95²⁰ ≈ 0.358; the chance that at least one does is 1 − 0.358 = 0.642. For 18 tests it is 1 − 0.95¹⁸ ≈ 0.60. So Caravan's February is the kind of result that would probably show up somewhere even if nothing were wrong.
The simplest correction is called the Bonferroni correction: if you run m tests, judge each test with the threshold α / m instead of α. With 20 tests the threshold is 0.05 / 20 = 0.0025. The last line of the simulation shows that with this threshold the share of "at least one false alarm" falls to 4.5%, which is again about α for the whole analysis. For Bazaar's 18 cells the threshold is 0.05 / 18 ≈ 0.0028, and Caravan's 0.035 is far above it. Bonferroni has a cost: the tighter the threshold, the higher the chance of missing real differences (the type II error from lesson 33). That is why there is a second, stronger rule: separate discovery from confirmation. Looking at many cells is not forbidden; it is how you find something interesting. But what you find is a discovery. To confirm it, you test it as a single hypothesis, written in advance, on new data (for example, the July–August orders).
Change the number of tests yourself:
Try it now· not graded; doesn't affect progress
With m = 5 the chance of at least one false alarm is about 22%, and with m = 50 it is about 92%. In all three cases Bonferroni pulls this share below 5%.
Why does it matter? When you compare two rates, the word "difference" can describe two different things, and the distance between them can be very large. You saw this in the A/B test in the previous lesson: the purchase rate was 13% on the old checkout page and 8% on the new one. The draft says "lowered it by only 5%."
The subtraction difference between two rates is described in percentage points (points for short): 13 − 8 = 5 points. The ratio of the change to the starting value is the relative change: 5 / 13 ≈ 0.385, that is, 38.5%. When someone says "fell by 5 percent," the reader understands the relative change: like going from 100 buyers to 95. In reality, it went from 100 buyers to about 62. The word "only" is built on this wrong reading.
old = 0.13 new = 0.08 points = (old - new) * 100 relative = (old - new) / old * 100 print("Absolute difference:", round(points, 1), "points") print("Relative drop: " + str(round(relative, 1)) + "%") rate_before = 10 rate_after = 12 print("Interest rate:", rate_after - rate_before, "points up | relative increase: " + str(round((rate_after / rate_before - 1) * 100, 1)) + "%")
OutputAbsolute difference: 5.0 points
Relative drop: 38.5%
Interest rate: 2 points up | relative increase: 20.0%The last line is an example outside the case: when a loan's interest rate goes from 10% to 12%, saying "the rate rose by 2%" is wrong; the rate rose by 2 points, or 20% in relative terms. On the other hand, with small rates the relative change can look frightening: if the rate of a side effect goes from 1 in 1,000 to 2 in 1,000, "the risk rose by 100%" is true, but the absolute increase is only 1 in 1,000. A good report gives both: "from 13% to 8%, 5 points; 38.5% in relative terms." The reader sees both the scale and the size.
Why does it matter? In lesson 10 you found three changes on the same day as the May drop: the ads were cut, the new mobile checkout page opened, and Electronics prices went up. The draft blames the whole drop on one cause, the ads. If two things changed at the same time, a before-and-after comparison cannot separate their effects. To separate them, you need a group that was affected by only one of the changes.
Bazaar has such a group. Cutting the ads affects both devices: a customer who comes through an ad can arrive from desktop or from mobile. The new checkout page, however, opened only on mobile. So desktop can be used like a control group that the checkout page did not affect. The drop of desktop gives us an estimate for the question "if there had been no new checkout page and only the ads had been cut, how much would mobile have dropped?" The drop of mobile beyond this can be attributed to the change specific to mobile.
The two periods have different numbers of months (January–April is 4 months, May–June is 2), so we convert totals to monthly averages. The crosstab from lesson 8 gives the period × device count table:
import pandas as pd orders = pd.read_csv("orders.csv") orders["period"] = "before" orders.loc[orders["date"] >= "2026-05-01", "period"] = "after" counts = pd.crosstab(orders["period"], orders["device"]) monthly_before = counts.loc["before"] / 4 monthly_after = counts.loc["after"] / 2 print(pd.DataFrame({"before (monthly)": monthly_before, "after (monthly)": monthly_after})) change = (monthly_after / monthly_before - 1) * 100 print(change.round(1)) diff = change["mobile"] - change["desktop"] print("Difference-in-differences (points):", round(diff, 1))
Output before (monthly) after (monthly)
device
desktop 65.50 53.5
mobile 101.75 54.5
device
desktop -18.3
mobile -46.4
dtype: float64
Difference-in-differences (points): -28.1On desktop, monthly orders fell from 65.5 to 53.5: a drop of 18.3%. This is the estimate for the ad cut (and the other shared effects in the same period). Mobile fell from 101.75 to 54.5: 46.4%. If mobile had been affected only by the shared effects, it would also have fallen by about 18%, to about 83 orders a month (101.75 × 0.817). In reality it fell to 54.5. The gap, −46.4 − (−18.3) ≈ −28 points, is the extra drop specific to mobile. The difference between the before-and-after changes of the two groups is called difference-in-differences: the first difference is each group's own change, and the second difference is the difference of these two changes.
This result splits the draft's sentence into two parts: the ad cut is consistent with a drop of about 18% on both devices, and the rest of the drop on mobile (about 28 points) is consistent with what changed on mobile on the same day, the new checkout page. The A/B test in the previous lesson had also shown that the new page lowered purchases, so two separate pieces of evidence point in the same direction.
Difference-in-differences rests on an assumption: parallel trends. We assume that without the change, the two groups would have moved by the same rate. You cannot see this assumption directly (the change happened), but you can support or weaken it by looking at whether the two groups followed a similar path in the period before the change. Let's scale each device's monthly orders so that January = 100:
import pandas as pd orders = pd.read_csv("orders.csv") orders["month"] = pd.to_datetime(orders["date"]).dt.month t = pd.crosstab(orders["month"], orders["device"]) before = t.loc[1:4] print((before / before.loc[1] * 100).round(0))
Outputdevice desktop mobile
month
1 100.0 100.0
2 112.0 117.0
3 91.0 131.0
4 100.0 109.0In raw counts, desktop is 65, 73, 59, 65 and mobile is 89, 104, 117, 97. In February both rise together, in April both fall together, but in March they separate (desktop 91, mobile 131). The paths are roughly similar, but mobile is more volatile. This does not refute the assumption, but it does not fully confirm it either; in the report you write, "before the change the two devices followed roughly similar paths; mobile was more volatile." There is one more limitation: the Electronics price increase. In lesson 37 you saw that 29.5% of desktop orders were Electronics, against only 9.1% of mobile orders. If the increase affected desktop more, the drop of the control group includes more than the ads, and the extra drop specific to mobile could be even larger than 28 points. The last assumption is this: on May 1, nothing on mobile changed except the checkout page.
Repeat the calculation category by category. First run it as it is, then change the category line:
Try it now· not graded; doesn't affect progress
In all five categories mobile falls harder than desktop; the gap is −13.5 points for Books and −59.3 points for Electronics. In Electronics, mobile orders are few to begin with, so this number is very volatile; still, the fact that the direction is the same in every category shows that the drop does not come from a single category.
Put the steps in the right order:
Put the steps in the right order when separating two effects with difference-in-differences.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Recognize the six flaws in sentences outside Bazaar. The list also has a distractor: Simpson's paradox from lesson 37 is not the flaw in any of these sentences.
Which fallacy is each flawed sentence an example of?
For each row, pick its match from the list, then check.
A city built bike lanes on three streets and made a statement a year later: "Bike lanes reduced accidents by 35%." The streets chosen for lanes were the streets with the most accidents in the previous year. This sentence contains two familiar flaws. The first is regression to the mean: if the streets with the most accidents were chosen, accident counts would probably have fallen the next year even if nothing had been done. The second is the lack of a control group: something else that year (a dry year, a new speed limit) may have reduced accidents on all streets.
The solution to both is the same: take streets that were chosen by the same criterion (high accidents in the previous year) but did not get a bike lane as the control group. Let's assume the city has three such streets (fictional sample data):
import pandas as pd accidents = pd.DataFrame({ "street": ["A", "B", "C", "D", "E", "F"], "group": ["lane built"] * 3 + ["no lane"] * 3, "before": [30, 26, 24, 29, 27, 22], "after": [19, 17, 16, 21, 18, 17], }) summary = accidents.groupby("group")[["before", "after"]].mean() summary["change_%"] = ((summary["after"] / summary["before"] - 1) * 100).round(1) print(summary.round(2)) diff = summary.loc["lane built", "change_%"] - summary.loc["no lane", "change_%"] print("Difference-in-differences (points):", round(diff, 1))
Output before after change_%
group
lane built 26.67 17.33 -35.0
no lane 26.00 18.67 -28.2
Difference-in-differences (points): -6.8On streets that did not get a lane but were chosen in the same way, accidents also fell by 28%. Most of the 35% drop can be explained by regression to the mean and by changes across the whole city; the extra drop that can be attributed to the bike lane is about 7 points. This is not certain either: with three streets, the share of luck is large, and for parallel trends you also need to look at the data of earlier years. But it is a much more honest start than "reduced by 35%."
The city's press office asks you before it makes the statement "Bike lanes reduced accidents by 35%." The three streets with lanes were the streets with the most accidents the year before.
Pick an option and see what happens. There are no points; you can try the other options too.
All six sentences of the draft report came from correct calculations; each said something the calculation does not say. Let's turn the question for each one into a checklist:
1. Who was measured? Is getting into the sample related to the result? (selection bias)
2. Who chose the period, and when? Were the start and end chosen before looking at the result, and with a reason? (cherry-picking)
3. Did I choose the group by its extreme value? If so, expect regression to the mean; is there a control group? (regression to the mean)
4. How many tests did I look at? Count what you looked at, not what you reported; judge with α / m and confirm the discovery on new data. (multiple comparisons)
5. Is the difference in points or relative? Write both. (percent vs. percentage points)
6. What else changed at the same time? Can you build a difference-in-differences with an unaffected group? (blaming one cause)
These six questions will be the checklist for the report in the next lesson, the capstone project. There you will write Bazaar's six-month story from start to finish yourself, and you will pass every sentence through this list. Let's end with the first question of the lesson: when you see a number, before you write a sentence, ask: what else could explain this number?
A researcher tested the link between six foods and a health measure separately and found these p-values (fictional sample data). Filtering a NumPy array with a condition (lesson 26) shows the two thresholds side by side:
import numpy as np p = np.array([0.03, 0.001, 0.2, 0.0024, 0.04, 0.011]) m = len(p) threshold = 0.05 / m print("Number of tests:", m, "| Bonferroni threshold:", round(threshold, 4)) print("Below 0.05:", p[p < 0.05]) print("Significant after Bonferroni:", p[p < threshold])
OutputNumber of tests: 6 | Bonferroni threshold: 0.0083
Below 0.05: [0.03 0.001 0.0024 0.04 0.011 ]
Significant after Bonferroni: [0.001 0.0024]With the 0.05 threshold, five of the six tests look "significant"; with the Bonferroni threshold of 0.0083, only two remain. Those two are also a discovery: they must be tested in a new study, with hypotheses written in advance.
The price of a stock over seven weeks (fictional sample data). The same last price produces two opposite headlines depending on the starting point:
price = [100, 92, 75, 60, 70, 84, 96] last = price[-1] low = min(price) print("From the low to today:", round((last / low - 1) * 100, 1), "%") print("From the start to today:", round((last / price[0] - 1) * 100, 1), )
When you apply Bonferroni, counting only the reported tests. If the analyst looked at 18 cells and put only the significant one in the report, calculating the threshold for that single test makes the correction useless:
reported_p = [0.0352] number_of_tests = 18 wrong_threshold = 0.05 / len(reported_p) right_threshold = 0.05 / number_of_tests print("Threshold if you count only the reported test:", wrong_threshold, "| significant?", reported_p[0] < wrong_threshold) print("Threshold if you count the 18 tests you looked at:", round(right_threshold, 4), "| significant?", reported_p[0] < right_threshold)
OutputThreshold if you count only the reported test: 0.05 | significant? True
Threshold if you count the 18 tests you looked at: 0.0028 | significant? Falsem is the number of tests you ran: every cell you looked at, every metric you tried, and every subgroup counts. The report should also say how many tests were looked at; only then can the reader ask, "did one of twenty tickets win?"
Next lesson: in the capstone project you will build Bazaar's six-month story yourself, from raw data to report, and pass every sentence through this six-question list.
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.
| Blaming one cause |
| "Two things changed on the same day. Desktop fell 18% and mobile fell 46%; the extra drop specific to mobile is about 28 points." |
OutputFrom the low to today: 60.0 %
From the start to today: -4.0 %"Up 60%" and "down 4%" are both true. Starting at the lowest point is the most common form of cherry-picking; an honest headline says why the period starts at that point.