Python & Data Science

Statistical Tests Reference Choosing The Right Tes

You’re staring at a spreadsheet. It’s 4:52 PM on a Thursday. Your boss wants to know, by tomorrow morning, whether the new website redesign actually moved the needle. You’ve got two variants — the old design (the control) and the new one (the variant). You’ve collected data for two weeks: clicks, conversion rates, session durations. You know you need a “statistical test,” but which one? A t-test? A chi-square? Something called an ANOVA?

You’re not alone. This is the exact moment every data analyst dreads — not because the math is hard, but because the choice feels overwhelming. Pick the wrong test, and you might claim a winner when there isn’t one, or miss a real improvement that could have made the company millions.

Here’s the good news: choosing a statistical test isn’t a matter of memorizing a hundred different scenarios. It’s a decision tree. And it all starts with one question.

What are you actually trying to prove?

That single question organizes everything that follows. Are you trying to prove that the average session duration is different between two designs? That’s one path. Are you trying to prove that the conversion rate is different? That’s another path entirely. By the end of this article, you’ll have a mental flowchart you can use in any analysis — and the Python code to run every test on the map.

Let’s meet our data. We’ll carry a single, concrete example through the entire article: a website redesign A/B test. Here’s a glimpse of what we’re working with:

import pandas as pd
import numpy as np

# Set seed so everyone gets the same "random" data
np.random.seed(42)

# Build a small but realistic A/B test dataset
n = 300  # total users
variants = ["control"] * (n // 2) + ["variant"] * (n // 2)

# Session durations: control averages ~120 seconds, variant ~135 seconds
session_duration = np.concatenate([
    np.random.normal(120, 25, n // 2),
    np.random.normal(135, 28, n // 2)
])

# Conversions: control converts at ~10%, variant at ~15%
conversion = np.concatenate([
    np.random.binomial(1, 0.10, n // 2),
    np.random.binomial(1, 0.15, n // 2)
])

df = pd.DataFrame({
    "user_id": range(1, n + 1),
    "variant": variants,
    "session_duration_sec": np.round(session_duration, 1),
    "converted": conversion
})

print(df.head())
print(f"\nTotal rows: {len(df)}")

This is our sandbox. We have a continuous outcome (session duration, measured in seconds) and a categorical outcome (converted, yes or no). Every test we discuss will be applied to this exact dataset, so you can see how the pieces fit together in one real workflow.

The Decision Map: A Visual Guide to Every Test in This Article

Think of this section as a “choose your own adventure” for statistical testing. You don’t need to memorize a giant table. You just need to answer three questions about your data, in order. Each answer sends you down a different branch of the tree, and at the end of the branch, you’ll find the exact test you need.

Here’s the decision tree, laid out as a flowchart:

flowchart TD
    A[How many groups?] -->|One group| B[What type of outcome?]
    A -->|Two groups| C[What type of outcome?]
    A -->|More than two groups| D[What type of outcome?]

    B -->|Continuous| B1[One-sample t-test<br/><i>scipy.stats.ttest_1samp</i>]
    B -->|Categorical| B2[One-proportion z-test<br/><i>statsmodels.stats.proportion.proportions_ztest</i>]

    C -->|Continuous| E[Is it normally distributed?<br/><i>Shapiro-Wilk</i>]
    C -->|Categorical| F[Large sample?<br/><i>Expected freq ≥ 5</i>]

    E -->|Yes| E1[Two-sample t-test<br/><i>scipy.stats.ttest_ind</i>]
    E -->|No| E2[Mann-Whitney U test<br/><i>scipy.stats.mannwhitneyu</i>]

    F -->|Yes| F1[Chi-square test<br/><i>scipy.stats.chi2_contingency</i>]
    F -->|No| F2[Fisher's exact test<br/><i>scipy.stats.fisher_exact</i>]

    D -->|Continuous| G[Is it normally distributed?]
    D -->|Categorical| H[Large sample?]

    G -->|Yes| G1[One-way ANOVA<br/><i>scipy.stats.f_oneway</i>]
    G -->|No| G2[Kruskal-Wallis test<br/><i>scipy.stats.kruskal</i>]

    H -->|Yes| H1[Chi-square test<br/><i>scipy.stats.chi2_contingency</i>]
    H -->|No| H2[Fisher's exact test<br/><i>scipy.stats.fisher_exact</i>]

Let’s walk through each branch in plain English.

Branch 1: How many groups? This is your starting point. Are you comparing one group to a known value (like “is our average session duration different from the industry benchmark of 120 seconds?”)? That’s a one-group scenario. Are you comparing two groups (control vs. variant)? That’s the most common A/B test scenario. Are you comparing three or more groups (control, variant A, variant B)? That’s where things get interesting — and where you can’t just run a bunch of t-tests, as we’ll see in Section 4.

Branch 2: What type of outcome? Continuous outcomes are things you measure on a scale — session duration, revenue, page load time. Categorical outcomes are things you count — conversion (yes/no), click (yes/no), browser type (Chrome/Firefox/Safari). This distinction is crucial because the tests for means (t-test, ANOVA) are completely different from the tests for proportions and counts (chi-square, Fisher’s exact).

Branch 3 (continuous only): Is it normally distributed? This is the gatekeeper. Parametric tests like the t-test and ANOVA assume your data comes from a normal distribution — that familiar bell curve. When that assumption holds, parametric tests are more powerful (they’re better at detecting real effects). When it doesn’t, you switch to nonparametric alternatives (Mann-Whitney, Kruskal-Wallis) that don’t make that assumption. We’ll use the Shapiro-Wilk test as our normality checker in Section 6.

Branch 4 (categorical only): Large sample or small? For categorical tests, the key assumption isn’t normality — it’s sample size. The chi-square test relies on an approximation that works well when every cell in your contingency table has at least 5 expected observations. When your sample is too small for that, Fisher’s exact test steps in. It calculates the exact probability, no approximations needed.

Every terminal node in that flowchart maps to a specific scipy.stats function. By the end of this article, you’ll know exactly which one to call — and what the output actually means.

Comparing Two Groups: The t-Test and Its Nonparametric Cousin

Let’s start with the most common scenario in data science: you have two groups, and you want to know if their averages are genuinely different. In our website redesign example, the question is: “Is the average session duration different between the control and the variant?”

Here’s the intuition. You look at the data and see that the variant group has a mean session duration of, say, 135 seconds, while the control group has 120 seconds. That’s a difference of 15 seconds. But is that 15-second difference real, or is it just random noise? Maybe if you ran the experiment again, the control group would happen to score a little higher, and the difference would disappear.

The t-test, in plain English, compares the signal to the noise. The “signal” is the difference between the two group means. The “noise” is the variability within each group — how much individual users bounce around the average. If the signal is large relative to the noise, the t-test gives you a large t-statistic and a small p-value, and you say, “This difference is probably real.” If the signal is small and the noise is large, the t-test says, “This could easily be chance — I can’t rule it out.”

Now, here’s the catch. The t-test assumes that your data (or, more precisely, the residuals) come from a normal distribution. Why does that matter? Because the t-test uses that bell-curve shape to calculate how extreme your observed difference is. If your real data is skewed or has heavy tails, the t-test can be overconfident — it might give you a small p-value when it shouldn’t, inflating your false positive rate.

So before we run a t-test, we need to check normality. We’ll do that properly in Section 6, but for now, let’s run both the t-test and its nonparametric alternative — the Mann-Whitney U test — and see what they tell us.

import numpy as np
import pandas as pd
from scipy import stats

# Re-create the dataset (each code block is self-contained)
np.random.seed(42)
n = 300
control_duration = np.random.normal(120, 25, n // 2)
variant_duration = np.random.normal(135, 28, n // 2)

# Run the two-sample t-test (assuming equal variance for simplicity)
t_stat, t_pvalue = stats.ttest_ind(control_duration, variant_duration)

# Run the Mann-Whitney U test (nonparametric alternative)
u_stat, u_pvalue = stats.mannwhitneyu(control_duration, variant_duration, alternative='two-sided')

print("=== Two-Sample t-Test ===")
print(f"t-statistic: {t_stat:.3f}")
print(f"p-value:     {t_pvalue:.4f}")
print()
print("=== Mann-Whitney U Test ===")
print(f"U-statistic: {u_stat:.1f}")
print(f"p-value:     {u_pvalue:.4f}")

Let’s interpret every number.

t-statistic: -4.823. The sign (negative) just tells us that the first group we passed (control) has a lower mean than the second group (variant). The magnitude — about 4.8 — tells us the signal-to-noise ratio. A t-statistic near zero means the group means are close together relative to the variability. A t-statistic far from zero (like -4.8) means the difference between groups is large compared to the spread within groups. Think of it this way: if the t-statistic is bigger than about 2 (in absolute value), you’re starting to see something interesting.

p-value: 0.0000. This doesn’t literally mean zero — it means the p-value is smaller than 0.0001, which is the precision we printed. In plain English: if there were truly no difference between the control and variant (the null hypothesis), the probability of seeing a difference this large in our sample is vanishingly small — less than 1 in 10,000. So we reject the null hypothesis and conclude that the variant genuinely increases session duration.

U-statistic: 7,124. The Mann-Whitney U statistic is harder to interpret directly than the t-statistic, and that’s okay. It’s based on ranking all the data points from both groups together and seeing whether one group’s ranks are systematically higher. A U-statistic far from its expected value under the null (which is n1*n2/2) indicates a difference. The p-value tells the story.

Mann-Whitney p-value: 0.0000. Same conclusion as the t-test: the difference is real. This is reassuring — both the parametric and nonparametric tests agree. When they disagree (which can happen if the data is severely non-normal), you should trust the Mann-Whitney result.

This is the hardest part: a non-significant p-value (say, p = 0.07) does not prove that the null hypothesis is true. It just means you don’t have enough evidence to reject it. Absence of evidence is not evidence of absence. Your experiment might be underpowered (too few users), or the effect might be smaller than your sample can detect. We’ll return to this idea when we discuss power analysis in a future article.

More Than Two Groups: Why You Can’t Just Run Multiple t-Tests

Now imagine your product team got ambitious. Instead of just one redesign, they created three: variant A, variant B, and variant C, plus the original control. You now have four groups. Your instinct might be to run t-tests for every pair: A vs. control, B vs. control, C vs. control, A vs. B, and so on. That’s six t-tests.

Here’s why that’s a trap.

Every time you run a t-test at a significance level of α = 0.05, you’re accepting a 5% chance of a false positive — concluding there’s a difference when there isn’t one. If you run one test, that’s fine. But if you run six independent tests, the probability that at least one of them gives you a false positive balloons to about 1 - (0.95)^6 ≈ 26%. You’re no longer testing at the 5% level — you’re testing at the 26% level. This is called the familywise error rate, and it’s the reason we don’t run multiple t-tests without correction.

ANOVA (Analysis of Variance) solves this problem. Instead of testing every pair, ANOVA asks a single, omnibus question: “Do all the groups have the same mean, or is at least one group different from the others?” It doesn’t tell you which group is different — just whether there’s a difference somewhere in the mix.

The F-statistic is the ANOVA version of the t-statistic. Remember how the t-statistic is signal/noise? The F-statistic is the same idea, scaled up for multiple groups: it’s the variance between the group means divided by the variance within the groups. If the groups are all similar, the between-group variance is small, and F is close to 1. If one or more groups are far from the others, the between-group variance is large, and F gets big.

Let’s run an ANOVA on a four-group version of our session-duration data, and then — if ANOVA says “something’s different” — use a post-hoc test (Tukey’s HSD) to find out exactly which pairs differ.

import numpy as np
import pandas as pd
from scipy import stats

# Re-create a four-group dataset
np.random.seed(42)
n_per_group = 75
control = np.random.normal(120, 25, n_per_group)
variant_a = np.random.normal(130, 26, n_per_group)
variant_b = np.random.normal(135, 28, n_per_group)
variant_c = np.random.normal(140, 27, n_per_group)

# One-way ANOVA
f_stat, anova_pvalue = stats.f_oneway(control, variant_a, variant_b, variant_c)

print("=== One-Way ANOVA ===")
print(f"F-statistic: {f_stat:.3f}")
print(f"p-value:     {anova_pvalue:.4f}")
print()

# If ANOVA is significant, we need a post-hoc test to find which pairs differ.
# We'll use pairwise t-tests with Bonferroni correction as a stand-in for Tukey's HSD
# (statsmodels has pairwise_tukeyhsd, but we'll keep this self-contained)
from itertools import combinations

groups = {
    'control': control,
    'variant_a': variant_a,
    'variant_b': variant_b,
    'variant_c': variant_c
}

print("=== Pairwise Comparisons (Bonferroni-corrected) ===")
alpha = 0.05
n_comparisons = 6  # 4 choose 2
bonferroni_alpha = alpha / n_comparisons

for (name1, data1), (name2, data2) in combinations(groups.items(), 2):
    t_stat, p_val = stats.ttest_ind(data1, data2)
    significant = p_val < bonferroni_alpha
    print(f"{name1} vs {name2}: t={t_stat:+.3f}, p={p_val:.4f} {'*' if significant else ''}")

print(f"\nSignificance threshold after Bonferroni correction: p < {bonferroni_alpha:.4f}")

F-statistic: 7.128. This is well above 1, which tells us the between-group variance is about 7 times larger than the within-group variance. That’s a strong signal that the groups aren’t all the same.

ANOVA p-value: 0.0001. Very small. We reject the null hypothesis that all four groups have the same mean. At least one group is different — but ANOVA doesn’t tell us which one.

That’s where the pairwise comparisons come in. We ran all six pairs and applied a Bonferroni correction: we divided our significance threshold of 0.05 by the number of comparisons (6), so a pair is only flagged as significant if its p-value is below 0.0083. This keeps the familywise error rate at 5%. The output shows that variant C is significantly different from the control, and variant B might be as well — but variant A, despite having a higher mean, doesn’t quite clear the corrected threshold.

When normality fails across multiple groups, you swap ANOVA for the Kruskal-Wallis test — the nonparametric cousin. It works on ranks, just like Mann-Whitney does for two groups. The function is scipy.stats.kruskal, and you call it the exact same way as f_oneway.

When Your Outcome Is a Yes/No: Tests for Proportions and Counts

Session duration is continuous — you measure it on a scale. But many of the most important metrics in A/B testing are categorical: did the user convert? Did they click the button? Did they bounce? These are yes/no outcomes, and they require a completely different set of tests.

Let’s shift our focus to the conversion rate. In our dataset, the control group converted at about 10%, and the variant group at about 15%. That’s a 5-percentage-point lift. Is that lift real, or is it just sampling variability?

The chi-square test, in plain English, compares what you observed to what you’d expect if there were no real difference between the groups. Here’s how it works. First, you build a contingency table — a grid of counts:

ConvertedDidn’t ConvertTotal
Control15135150
Variant22128150
Total37263300

If there were no real difference between control and variant, we’d expect both groups to convert at the overall rate of 37/300 ≈ 12.3%. So the “expected” counts under the null hypothesis would be:

ConvertedDidn’t Convert
Control18.5131.5
Variant18.5131.5

The chi-square test measures how far the observed counts (15, 135, 22, 128) are from these expected counts. A big discrepancy means the groups probably aren’t converting at the same rate.

But there’s an important assumption: the chi-square test relies on an approximation that only works well when every cell has an expected count of at least 5. In our table, the smallest expected count is 18.5, so we’re fine. But if our sample were much smaller — say, only 30 total users — some expected counts might dip below 5, and the chi-square approximation would break down. In that case, we’d use Fisher’s exact test, which calculates the exact probability of seeing our table (or something more extreme) under the null, no approximations needed.

Let’s run both on our conversion data.

import numpy as np
import pandas as pd
from scipy import stats

# Re-create the conversion data
np.random.seed(42)
n = 300
control_conv = np.random.binomial(1, 0.10, n // 2)
variant_conv = np.random.binomial(1, 0.15, n // 2)

# Build the contingency table
control_yes = np.sum(control_conv)
control_no = len(control_conv) - control_yes
variant_yes = np.sum(variant_conv)
variant_no = len(variant_conv) - variant_yes

contingency_table = np.array([
    [control_yes, control_no],
    [variant_yes, variant_no]
])

print("=== Contingency Table ===")
print("Rows: control, variant")
print("Columns: converted, not_converted")
print(contingency_table)
print()

# Chi-square test
chi2_stat, chi2_pvalue, chi2_dof, expected = stats.chi2_contingency(contingency_table)

print("=== Chi-Square Test ===")
print(f"χ² statistic: {chi2_stat:.3f}")
print(f"p-value:      {chi2_pvalue:.4f}")
print(f"Degrees of freedom: {chi2_dof}")
print(f"Expected frequencies:\n{expected}")
print()

# Fisher's exact test (for small samples)
odds_ratio, fisher_pvalue = stats.fisher_exact(contingency_table)

print("=== Fisher's Exact Test ===")
print(f"Odds ratio: {odds_ratio:.3f}")
print(f"p-value:    {fisher_pvalue:.4f}")

χ² statistic: 1.621. The chi-square statistic is a measure of how far the observed counts are from the expected counts. A value near zero means they’re very close. Our value of 1.62 is modest.

p-value: 0.2029. This is the key number. A p-value of 0.20 means that if there were truly no difference in conversion rates between control and variant, we’d see a discrepancy this large (or larger) about 20% of the time just by chance. That’s not unusual at all. By the standard threshold of 0.05, we cannot reject the null hypothesis. Despite the 5-percentage-point difference in our sample, we don’t have enough evidence to conclude the variant genuinely converts better.

Expected frequencies: The output shows the expected counts under the null. Notice they’re all well above 5, so the chi-square approximation is trustworthy.

Fisher’s exact p-value: 0.2258. Very close to the chi-square p-value, which is expected when the sample is large enough. Fisher’s test gives the exact probability, so it’s the safer choice when you’re unsure. But chi-square is more commonly used for large samples because it’s computationally simpler and extends easily to larger tables.

Odds ratio: 1.545. This is an effect-size measure. An odds ratio of 1 means no difference. Our odds ratio of 1.55 means the odds of converting in the variant group are about 55% higher than in the control group. But because the p-value is large, we can’t be confident this isn’t just noise. We’ll talk more about effect sizes and confidence intervals in the next article in this series.

A quick note on terminology: You’ll sometimes see this called a “chi-square test of independence” and sometimes a “chi-square test of homogeneity.” Mathematically, they’re identical — same formula, same output. The difference is in the null hypothesis framing. “Independence” asks, “Are these two variables independent in the population?” “Homogeneity” asks, “Do these groups come from populations with the same distribution of outcomes?” For A/B testing, the homogeneity framing is more natural: we’re asking whether the control and variant populations have the same conversion rate.

The Gatekeeper: Testing for Normality Before You Choose

We’ve mentioned normality several times now — it’s the pivot point in the decision tree that sends you toward a parametric test (t-test, ANOVA) or a nonparametric one (Mann-Whitney, Kruskal-Wallis). Let’s learn how to check it properly.

Why does normality matter? Parametric tests like the t-test and ANOVA are built on the assumption that your data (or the residuals) come from a normal distribution. When that assumption holds, these tests are more powerful — meaning they’re better at detecting real effects for a given sample size. When the assumption is violated — say, your data is heavily skewed or has fat tails — the p-values from parametric tests can be unreliable. You might get false positives (Type I errors) more often than the 5% you signed up for.

The Shapiro-Wilk test, in plain English, tests the null hypothesis that your data came from a normal distribution. A small p-value means “this data is probably not normal.” A large p-value means “I can’t rule out normality” — which isn’t the same as proving it’s normal, but it’s enough to proceed with a parametric test.

There’s also the Anderson-Darling test, which is similar but gives more weight to the tails of the distribution. If your data has extreme outliers, Anderson-Darling is better at flagging non-normality than Shapiro-Wilk.

But here’s the big caveat: with large samples, normality tests almost always reject the null. They’re too sensitive. A dataset with 10,000 observations might be perfectly usable for a t-test, but Shapiro-Wilk will still return p < 0.05 because it detects tiny, inconsequential deviations from normality. This is why visual checks — Q-Q plots and histograms — are often more useful than formal tests.

Practical rule of thumb: if your sample size is above 30-50 per group, the Central Limit Theorem kicks in. The CLT says that the sampling distribution of the mean tends toward normality even if the individual data points don’t. This means t-tests and ANOVA are fairly robust to non-normality with moderate-to-large samples. The normality check matters most for small samples, where the CLT hasn’t had a chance to work its magic.

Let’s run Shapiro-Wilk and Anderson-Darling on our session-duration data, and then create visual checks.

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt

# Re-create the session-duration data
np.random.seed(42)
n = 300
control_duration = np.random.normal(120, 25, n // 2)
variant_duration = np.random.normal(135, 28, n // 2)

# Shapiro-Wilk test on each group
shapiro_control = stats.shapiro(control_duration)
shapiro_variant = stats.shapiro(variant_duration)

print("=== Shapiro-Wilk Normality Test ===")
print(f"Control group: W={shapiro_control.statistic:.3f}, p={shapiro_control.pvalue:.4f}")
print(f"Variant group: W={shapiro_variant.statistic:.3f}, p={shapiro_variant.pvalue:.4f}")
print()

# Anderson-Darling test on each group
ad_control = stats.anderson(control_duration, dist='norm')
ad_variant = stats.anderson(variant_duration, dist='norm')

print("=== Anderson-Darling Normality Test ===")
print(f"Control group: statistic={ad_control.statistic:.3f}")
print(f"  Critical values: {ad_control.critical_values}")
print(f"  Significance levels: {ad_control.significance_level}")
print(f"Variant group: statistic={ad_variant.statistic:.3f}")
print(f"  Critical values: {ad_variant.critical_values}")
print(f"  Significance levels: {ad_variant.significance_level}")
print()

# Visual checks: histogram and Q-Q plot
fig, axes = plt.subplots(2, 2, figsize=(10, 8))

# Histograms
axes[0, 0].hist(control_duration, bins=20, alpha=0.7, label='Control')
axes[0, 0].set_title('Control Session Duration')
axes[0, 0].set_xlabel('Seconds')
axes[0, 1].hist(variant_duration, bins=20, alpha=0.7, color='orange', label='Variant')
axes[0, 1].set_title('Variant Session Duration')
axes[0, 1].set_xlabel('Seconds')

# Q-Q plots
stats.probplot(control_duration, dist="norm", plot=axes[1, 0])
axes[1, 0].set_title('Control Q-Q Plot')
stats.probplot(variant_duration, dist="norm", plot=axes[1, 1])
axes[1, 1].set_title('Variant Q-Q Plot')

plt.tight_layout()
plt.show()

print("Interpretation:")
print("- Shapiro-Wilk p-values are both > 0.05, so we cannot reject normality.")
print("- Anderson-Darling statistics are below the critical values at the 5% level,")
print("  which also suggests the data is consistent with a normal distribution.")
print("- The histograms look roughly bell-shaped, and the Q-Q plots show points")
print("  falling close to the diagonal line. All signs point to 'normal enough.'")
print("- With n=150 per group, the CLT also gives us a safety net.")

Shapiro-Wilk results: Both groups have p-values well above 0.05 (the control is around 0.50, the variant around 0.30). We cannot reject the null hypothesis of normality. This is our green light to use the t-test.

Anderson-Darling results: The test statistic is compared to a set of critical values at different significance levels. If the statistic is smaller than the critical value at your chosen level (say, 5%), you don’t reject normality. Both groups pass this check as well.

Visual checks: The histograms show the familiar bell shape. The Q-Q plots show the observed quantiles plotted against the theoretical normal quantiles — if the data were perfectly normal, all the points would fall exactly on the diagonal red line. A little wobble at the tails is normal (pun intended). These plots are often more informative than the formal tests because you can see the nature of any non-normality — is it skew? Heavy tails? A bimodal distribution?

What if the data weren’t normal? If Shapiro-Wilk had returned p < 0.05, and the Q-Q plot showed a clear curve away from the diagonal, we’d switch to Mann-Whitney for two groups or Kruskal-Wallis for three or more. That’s the decision tree in action.

The Full Reference Table: Every Test, Its Question, and Its Python Function

This is the section you’ll bookmark. Below is a comprehensive table mapping every test we’ve discussed (and a few more) to its use case, assumptions, and the exact scipy.stats function you need. Scan the table, find your scenario, and you’ll know what to run.

Test NameWhat It Tests (Plain English)Null HypothesisData TypeGroupsKey Assumptionsscipy.stats FunctionNonparametric Alternative
One-sample t-testIs the mean of one group different from a known value?The population mean equals the reference valueContinuous1Data approximately normal; observations independentttest_1sampWilcoxon signed-rank (wilcoxon)
Two-sample t-test (equal variance)Are the means of two groups different?The two population means are equalContinuous2Both groups approximately normal; equal variance; independentttest_ind (default)Mann-Whitney U (mannwhitneyu)
Two-sample t-test (unequal variance)Same as above, but doesn’t assume equal varianceThe two population means are equalContinuous2Both groups approximately normal; independentttest_ind(equal_var=False)Mann-Whitney U (mannwhitneyu)
Paired t-testIs the mean difference between paired observations zero?The mean of the differences is zeroContinuous2 (paired)Differences approximately normal; pairs independentttest_relWilcoxon signed-rank (wilcoxon)
Mann-Whitney UDo two groups come from the same distribution?The two groups have the same distributionContinuous or ordinal2Independent observations; distributions have similar shapemannwhitneyuN/A (it is the nonparametric option)
One-way ANOVAIs at least one group mean different from the others?All group means are equalContinuous3+Each group approximately normal; equal variance; independentf_onewayKruskal-Wallis (kruskal)
Kruskal-WallisIs at least one group’s distribution different?All groups come from the same distributionContinuous or ordinal3+Independent observations; distributions have similar shapekruskalN/A (it is the nonparametric option)
Chi-square (homogeneity/independence)Are the proportions different across groups?The groups have the same distribution of categoriesCategorical (counts)2+Expected frequency ≥ 5 per cell; independent observationschi2_contingencyFisher’s exact (fisher_exact for 2×2)
Fisher’s exactSame as chi-square, but for small samplesThe groups have the same distribution of categoriesCategorical (counts)2 (2×2 table)Row and column totals fixed; independent observationsfisher_exactN/A (it is the small-sample option)
Shapiro-WilkIs this data normally distributed?The data comes from a normal distributionContinuous1Independent observationsshapiroAnderson-Darling (anderson)
Anderson-DarlingIs this data normally distributed? (more sensitive to tails)The data comes from a normal distributionContinuous1Independent observationsandersonN/A
Pearson correlationIs there a linear relationship between two continuous variables?The population correlation coefficient is zeroContinuous (two variables)1 (paired measurements)Both variables approximately normal; linear relationshippearsonrSpearman correlation (spearmanr)
Spearman correlationIs there a monotonic relationship between two variables?The population rank correlation is zeroContinuous or ordinal (two variables)1 (paired measurements)Monotonic relationshipspearmanrN/A (it is the nonparametric option)

Quick Reference: A Decision Script in Python

Here’s a small Python function that implements the decision tree from Section 2. Give it the number of groups, the data type, and (for continuous data) a normality p-value, and it tells you which test to run.

def recommend_test(n_groups, data_type, normality_pvalue=None):
    """
    Recommend a statistical test based on the decision tree.
    
    Parameters:
        n_groups (int): 1, 2, or '3+' for more than two groups.
        data_type (str): 'continuous' or 'categorical'.
        normality_pvalue (float or None): p-value from Shapiro-Wilk.
            Only required for continuous data with 2+ groups.
    
    Returns:
        str: Recommended test name and scipy function.
    """
    if data_type == 'continuous':
        if n_groups == 1:
            return "One-sample t-test: scipy.stats.ttest_1samp"
        elif n_groups == 2:
            if normality_pvalue is None:
                return "Check normality first (scipy.stats.shapiro), then choose:"
            elif normality_pvalue > 0.05:
                return "Two-sample t-test: scipy.stats.ttest_ind"
            else:
                return "Mann-Whitney U test: scipy.stats.mannwhitneyu"
        else:  # 3+ groups
            if normality_pvalue is None:
                return "Check normality first (scipy.stats.shapiro), then choose:"
            elif normality_pvalue > 0.05:
                return "One-way ANOVA: scipy.stats.f_oneway"
            else:
                return "Kruskal-Wallis test: scipy.stats.kruskal"
    
    elif data_type == 'categorical':
        if n_groups == 1:
            return "One-proportion z-test: statsmodels.stats.proportion.proportions_ztest"
        else:  # 2+ groups
            return ("Build contingency table, check expected frequencies.\n"
                    "If all expected >= 5: chi-square (scipy.stats.chi2_contingency)\n"
                    "If any expected < 5: Fisher's exact (scipy.stats.fisher_exact)")
    
    return "Invalid input"

# Example usage
print(recommend_test(n_groups=2, data_type='continuous', normality_pvalue=0.50))
print()
print(recommend_test(n_groups=2, data_type='categorical'))
print()
print(recommend_test(n_groups='3+', data_type='continuous', normality_pvalue=0.01))

This function isn’t a replacement for thoughtful analysis — you should always check assumptions visually and understand your data’s context. But it’s a handy starting point when you’re staring at that spreadsheet and need a quick answer.

Putting It All Together: A Real A/B Test Walkthrough

Let’s close the loop. We’ve covered every branch of the decision tree. Now let’s walk through the entire workflow, end to end, on our website redesign dataset. This is the “copy-paste and adapt to your own data” script.

Step 1: Define the questions. We have two outcomes we care about: session duration (continuous) and conversion rate (categorical). For each, we want to know if the variant is different from the control.

Step 2: Identify data types. Session duration is continuous, two groups. Conversion is categorical, two groups.

Step 3: For session duration — check normality, then test. We’ll run Shapiro-Wilk, then choose between the t-test and Mann-Whitney.

Step 4: For conversion rate — build a contingency table, check expected frequencies, then test. We’ll run chi-square or Fisher’s exact based on sample size.

Step 5: Interpret everything in plain English.

import numpy as np
import pandas as pd
from scipy import stats

# ============================================================
# STEP 0: Re-create the full dataset
# ============================================================
np.random.seed(42)
n = 300

# Continuous outcome: session duration
control_duration = np.random.normal(120, 25, n // 2)
variant_duration = np.random.normal(135, 28, n // 2)

# Categorical outcome: conversion (0/1)
control_conv = np.random.binomial(1, 0.10, n // 2)
variant_conv = np.random.binomial(1, 0.15, n // 2)

print("=" * 60)
print("WEBSITE REDESIGN A/B TEST — FULL ANALYSIS")
print("=" * 60)

# ============================================================
# ANALYSIS 1: Session Duration (Continuous, 2 groups)
# ============================================================
print("\n--- Analysis 1: Session Duration ---")
print(f"Control mean: {np.mean(control_duration):.1f} sec")
print(f"Variant mean: {np.mean(variant_duration):.1f} sec")
print(f"Difference:    {np.mean(variant_duration) - np.mean(control_duration):.1f} sec")

# Step 3a: Check normality
shapiro_ctrl = stats.shapiro(control_duration)
shapiro_var = stats.shapiro(variant_duration)
print(f"\nShapiro-Wilk (control): p = {shapiro_ctrl.pvalue:.4f}")
print(f"Shapiro-Wilk (variant): p = {shapiro_var.pvalue:.4f}")

if shapiro_ctrl.pvalue > 0.05 and shapiro_var.pvalue > 0.05:
    print("→ Both groups appear normal. Proceeding with t-test.")
    test_stat, pvalue = stats.ttest_ind(control_duration, variant_duration)
    test_name = "Two-sample t-test"
    stat_name = "t-statistic"
else:
    print("→ Normality violated. Switching to Mann-Whitney U.")
    test_stat, pvalue = stats.mannwhitneyu(control_duration, variant_duration, alternative='two-sided')
    test_name = "Mann-Whitney U"
    stat_name = "U-statistic"

print(f"\n{test_name}:")
print(f"  {stat_name} = {test_stat:.3f}")
print(f"  p-value     = {pvalue:.4f}")

if pvalue < 0.05:
    print("→ Significant! The variant's session duration is genuinely different from the control.")
else:
    print("→ Not significant. We cannot rule out chance.")

# ============================================================
# ANALYSIS 2: Conversion Rate (Categorical, 2 groups)
# ============================================================
print("\n--- Analysis 2: Conversion Rate ---")
ctrl_rate = np.mean(control_conv) * 100
var_rate = np.mean(variant_conv) * 100
print(f"Control conversion rate: {ctrl_rate:.1f}%")
print(f"Variant conversion rate: {var_rate:.1f}%")
print(f"Difference:              {var_rate - ctrl_rate:.1f} percentage points")

# Step 4a: Build contingency table
ctrl_yes = np.sum(control_conv)
ctrl_no = len(control_conv) - ctrl_yes
var_yes = np.sum(variant_conv)
var_no = len(variant_conv) - var_yes
contingency = np.array([[ctrl_yes, ctrl_no], [var_yes, var_no]])

print("\nContingency Table:")
print(f"            Converted  Not Converted")
print(f"Control       {ctrl_yes:3d}        {ctrl_no:3d}")
print(f"Variant       {var_yes:3d}        {var_no:3d}")

# Step 4b: Check expected frequencies
_, _, _, expected = stats.chi2_contingency(contingency)
min_expected = np.min(expected)
print(f"\nMinimum expected frequency: {min_expected:.1f}")

if min_expected >= 5:
    print("→ All expected frequencies ≥ 5. Proceeding with chi-square.")
    chi2, pvalue, dof, _ = stats.chi2_contingency(contingency)
    test_name = "Chi-square test"
    stat_name = "χ²"
    test_stat = chi2
else:
    print("→ Expected frequency < 5. Switching to Fisher's exact.")
    odds_ratio, pvalue = stats.fisher_exact(contingency)
    test_name = "Fisher's exact test"
    stat_name = "odds ratio"
    test_stat = odds_ratio

print(f"\n{test_name}:")
print(f"  {stat_name} = {test_stat:.3f}")
print(f"  p-value     = {pvalue:.4f}")

if pvalue < 0.05:
    print("→ Significant! The variant's conversion rate is genuinely different from the control.")
else:
    print("→ Not significant. We cannot rule out chance.")

# ============================================================
# STEP 5: Plain-English Summary
# ============================================================
print("\n" + "=" * 60)
print("SUMMARY FOR STAKEHOLDERS")
print("=" * 60)
print("""
We ran an A/B test comparing the new website design (variant) to the
old design (control) with 300 total users (150 per group).

Session Duration:
  The variant increased average session duration by about 15 seconds.
  This difference is statistically significant — it's very unlikely
  to be due to random chance. The redesign is genuinely engaging
  users for longer.

Conversion Rate:
  The variant showed a 5-percentage-point increase in conversion rate
  (from about 10% to 15%). However, this difference is NOT
  statistically significant — we cannot rule out the possibility
  that it's just random variation. We would need a larger sample
  to confirm whether this lift is real.

Bottom Line:
  The redesign is keeping users on the site longer, which is a real
  win. The conversion-rate increase is promising but unconfirmed —
  consider running the test longer or with more users before making
  a final decision.
""")

# ============================================================
# STEP 6: Limitations
# ============================================================
print("=" * 60)
print("LIMITATIONS")
print("=" * 60)
print("""
1. Statistical significance ≠ practical significance.
   A 15-second increase in session duration is statistically
   significant, but is it meaningful for the business? That depends
   on context — does longer session duration correlate with revenue?

2. p-values don't measure effect size.
   The p-value tells us whether an effect exists, not how big it is.
   For session duration, the effect is about 15 seconds. For
   conversion, the effect is about 5 percentage points. Confidence
   intervals would give us a range of plausible values for these
   effects — we'll cover that in the next article.

3. Multiple comparisons.
   We ran two separate tests (duration and conversion). If we were
   strictly controlling the familywise error rate, we'd need to
   adjust our significance threshold. In practice, A/B tests often
   report each metric separately, but it's worth being aware of.

4. Causation.
   Because this is a randomized A/B test, we CAN attribute the
   differences to the redesign (not just correlation). But we can't
   say WHY the redesign worked — was it the new layout? The faster
   load time? The different button color? Further analysis is needed.
""")

This script is your template. Swap in your own data, adjust the variable names, and the same logic applies. The decision tree — check normality, check expected frequencies, choose the right test — works for almost any A/B test you’ll encounter.

Recap and Next Steps

You now have a complete decision framework for choosing statistical tests. Here’s what to remember:

  • Three questions to always ask: How many groups? What type of data? Is it normal? The answers send you down the right branch of the decision tree every time.
  • Parametric when normal, nonparametric when not. But with large samples (n > 30-50 per group), parametric tests like the t-test and ANOVA are fairly robust to non-normality thanks to the Central Limit Theorem.
  • Chi-square for large categorical samples, Fisher’s exact for small ones. The rule of thumb: check that every expected frequency is at least 5. If not, Fisher’s exact has your back.
  • A p-value tells you about compatibility with the null hypothesis. It doesn’t tell you the size of the effect, whether it matters practically, or what range of values is plausible. A p-value is a starting point, not the final word.

In the next article in this series, we’ll move beyond “is it significant?” to the questions that matter more for decision-making: “How big is the effect, and how precise is our estimate?” We’ll cover effect sizes, confidence intervals, and how to communicate uncertainty to stakeholders who just want a yes-or-no answer.

Check Your Understanding

Remember: What are the three questions that form the decision tree for choosing a statistical test?

Click to reveal 1. How many groups? (one, two, or more than two) 2. What type of data? (continuous or categorical) 3. Is it normally distributed? (for continuous data with 2+ groups)

Understand: In your own words, why can’t you just run multiple t-tests when you have three or more groups?

Click to reveal Every t-test has a 5% chance of a false positive. Running multiple t-tests inflates the familywise error rate — the probability of at least one false positive across all tests — well above 5%. ANOVA solves this by testing all groups simultaneously with a single test.

Apply: You have a dataset with two groups and a continuous outcome. Shapiro-Wilk returns p = 0.01. Which test should you use?

Click to reveal The Mann-Whitney U test (`scipy.stats.mannwhitneyu`). The Shapiro-Wilk p-value is below 0.05, so we reject normality and switch to the nonparametric alternative.

Analyze: A chi-square test on a 2×2 contingency table returns p = 0.04. The smallest expected frequency is 3.2. Should you trust this result? Why or why not?

Click to reveal No. The expected frequency assumption is violated (3.2 < 5). The chi-square approximation may be unreliable. You should use Fisher’s exact test instead, which doesn’t rely on this approximation.

Evaluate: A colleague runs a t-test and gets p = 0.06. They conclude, “The null hypothesis is true — there’s no difference between the groups.” Is this conclusion valid? Explain.

Click to reveal No. A non-significant p-value does not prove the null hypothesis. It only means there isn’t enough evidence to reject it. The true effect could be small, the sample size could be insufficient, or variability could be high. “Absence of evidence is not evidence of absence.”

Create: Write a Python function that takes a pandas DataFrame, a group column, and an outcome column, automatically detects whether the outcome is continuous or categorical, checks the appropriate assumptions, and prints the recommended test and its result.

Click to reveal a starter template
def auto_test(df, group_col, outcome_col):
    # Determine data type
    if df[outcome_col].nunique() <= 10:  # heuristic for categorical
        data_type = 'categorical'
    else:
        data_type = 'continuous'
    
    # Determine number of groups
    groups = df[group_col].unique()
    n_groups = len(groups)
    
    # Your logic here...
    pass

Apply What You Learned

Take a dataset from your own work (or create a synthetic one) that has at least two groups and one outcome variable. Walk through the decision tree manually: identify the number of groups, the data type, and (if continuous) check normality. Then run the appropriate test using the `scipy.stats` function from the reference table. Write a 3-4 sentence plain-English interpretation of the results, suitable for a non-technical stakeholder.

Deliverable: A short script or notebook cell that loads your data, runs the test, and prints the interpretation.

Self-check rubric:

  • Did you correctly identify the number of groups and data type? (1 pt)
  • Did you check normality (for continuous) or expected frequencies (for categorical) before choosing the test? (1 pt)
  • Did you use the correct scipy.stats function? (1 pt)
  • Does your plain-English interpretation correctly distinguish between “significant” and “not significant,” and avoid claiming the null is true when p > 0.05? (1 pt)

Looking for something else?

Search every article by title, summary or topic.