SkillNavora
AI-First Data Engineer › ML class guide › Companion lesson 1 of 6

Hypothesis-testing case study: did the card campaign work?

One business case, every test from Classes 1 to 3: one-sample, paired and independent t-tests, ANOVA, chi-square and correlation, each with its hypotheses, p-value and plain-English decision.

Best read after Statistics & Machine Learning 5: Hypothesis Testing II: Chi-Square, ANOVA, Non-Parametric Tests and Correlation Tests in the Data Science & AI handbook.

In plain words. A court case. The null hypothesis is "innocent until proven guilty": nothing changed. The data is the evidence. The p-value says how surprising the evidence would be if nothing had changed. Alpha (5%) is how much risk of convicting an innocent person you accept.

1. Why it matters

  • Marketing, HR and finance teams ask "did it work?" every week. Hypothesis tests answer with evidence instead of opinion.
  • Picking the wrong test (independent instead of paired, t-test instead of chi-square) gives the wrong answer with full confidence.
  • Interviewers often give exactly this kind of case and ask you to choose and justify the test.

2. Key ideas

Choosing the testNumeric vs a known value: one-sample t. Same people before and after: paired t. Two separate groups: independent t. Three or more groups: ANOVA. Two categorical variables: chi-square. Two numeric variables: correlation.
Z or t?Use z when the population standard deviation is known and n > 30; otherwise t. With large samples they agree (1.96 vs 1.97 here).
H0 and HaH0 says nothing changed or there is no relationship. Ha is the claim you want evidence for. The test never proves H0; it only fails to reject it.
alpha and confidencealpha = 1 - confidence. 5% for business decisions, 1% for health or critical finance.
p-valueThe probability of data at least this extreme if H0 were true. p < alpha: reject H0. It is not the probability that H0 is true.
One-tailed vs two-tailedTwo-tailed asks "is it different?"; one-tailed asks "is it higher?" (or lower). Decide before you look at the data.
Critical valueThe table value the test statistic must pass: z = 1.96 (two-tailed, 95%), chi-square = 12.59 for df = 6.
Assumptions and fallbackst-tests and ANOVA assume roughly normal data; if Shapiro-Wilk says no, use Wilcoxon, Mann-Whitney or Kruskal-Wallis.

3. Step by step

  1. Write the business question in one sentence ("Did usage rise after the campaign?").
  2. Identify the data type and design: numeric or categorical, same people or different groups, how many groups.
  3. Choose the test from the table above and write H0 and Ha.
  4. Fix alpha (0.05) and one- or two-tailed before running anything.
  5. Check assumptions (normality, equal variances); switch to the non-parametric test if they fail.
  6. Run the test, read the p-value, compare with alpha.
  7. Write the decision in business words: "Usage rose significantly in month 2 but not clearly in month 1."

4. Code you can run

Install once: pip install numpy pandas scipy scikit-learn statsmodels, then run python c1_hypothesis_case.py. The data is generated inside the script, so it runs anywhere.

c1_hypothesis_case.py
"""Hypothesis-testing case study: does a credit-card campaign change usage?
Synthetic data with the same structure as the class case (customer segments, regions,
usage before and after a campaign). Run: python c1_hypothesis_case.py"""
import numpy as np
import pandas as pd
from scipy import stats

rng = np.random.default_rng(7)
n = 200
df = pd.DataFrame({
    "cust_id": range(1, n + 1),
    "sex": rng.integers(0, 2, n),                 # 0 = male, 1 = female
    "region": rng.choice([1, 2, 3, 4], n),        # 1 North, 2 South, 3 East, 4 West
})
df["segment"] = np.where(df.region <= 2, rng.choice([1, 2, 3], n, p=[.5, .3, .2]), rng.choice([1, 2, 3], n, p=[.2, .3, .5]))
df["pre_usage"] = rng.normal(50, 12, n).round(1)
df["post_usage_1month"] = (df.pre_usage + rng.normal(0.6, 8, n)).round(1)      # tiny change
df["post_usage_2ndmonth"] = (df.pre_usage + rng.normal(4.0, 8, n)).round(1)   # real lift
df["latest_mon_usage"] = (df.post_usage_2ndmonth + df.segment * 3 + rng.normal(0, 6, n)).round(1)

print("Data audit:", df.shape, "| missing:", int(df.isnull().sum().sum()), "| duplicates:", int(df.duplicated().sum()))
ALPHA = 0.05  # 95% confidence
rows = []


def decide(name, h0, p, test):
    verdict = "Reject H0" if p < ALPHA else "Fail to reject H0"
    rows.append((name, test, h0, f"{p:.4f}", verdict))


# Q1 One-sample t-test: is the average post-campaign usage different from the old average of 50?
t, p = stats.ttest_1samp(df.post_usage_1month, popmean=50)
decide("Q1 sample vs population", "mean usage = 50", p, "one-sample t")

# Q2 Paired (dependent) t-test, one-tailed: did usage go UP in month 1?
t, p = stats.ttest_rel(df.post_usage_1month, df.pre_usage, alternative="greater")
decide("Q2 before vs after (month 1)", "post <= pre", p, "paired t, one-tailed")

# Q2b same question for month 2
t, p = stats.ttest_rel(df.post_usage_2ndmonth, df.pre_usage, alternative="greater")
decide("Q2b before vs after (month 2)", "post <= pre", p, "paired t, one-tailed")

# Q3 Independent two-sample t-test (Welch): do men and women use the card differently?
m, f = df.loc[df.sex == 0, "latest_mon_usage"], df.loc[df.sex == 1, "latest_mon_usage"]
t, p = stats.ttest_ind(m, f, equal_var=False)
decide("Q3 male vs female", "mean_m = mean_f", p, "independent t (Welch)")

# Q4 One-way ANOVA: is usage the same in all three segments?
groups = [g.latest_mon_usage for _, g in df.groupby("segment")]
F, p = stats.f_oneway(*groups)
decide("Q4 three segments", "all segment means equal", p, "one-way ANOVA")

# Q5 Chi-square test of independence: are segment and region related?
obs = pd.crosstab(df.region, df.segment)
chi2, p, dof, expected = stats.chi2_contingency(obs)
decide("Q5 segment vs region", "independent", p, f"chi-square (df={dof})")

# Q6 Correlation: does pre-campaign usage move with latest usage?
r, p = stats.pearsonr(df.pre_usage, df.latest_mon_usage)
decide(f"Q6 Pearson r = {r:.2f}", "no linear correlation", p, "Pearson")
rho, p = stats.spearmanr(df.pre_usage, df.latest_mon_usage)
decide(f"Q6b Spearman rho = {rho:.2f}", "no monotonic correlation", p, "Spearman")

print(f"\n{'Question':<30}{'Test':<24}{'H0':<26}{'p-value':<10}Decision (alpha 0.05)")
for r_ in rows:
    print(f"{r_[0]:<30}{r_[1]:<24}{r_[2]:<26}{r_[3]:<10}{r_[4]}")

# Assumption check and the non-parametric versions
w, p_norm = stats.shapiro(df.post_usage_1month - df.pre_usage)
print(f"\nShapiro-Wilk on paired differences: p = {p_norm:.3f} ({'looks normal' if p_norm > ALPHA else 'not normal: use Wilcoxon'})")
print(f"Wilcoxon signed-rank (month 2 > pre): p = {stats.wilcoxon(df.post_usage_2ndmonth, df.pre_usage, alternative='greater').pvalue:.2e}")
print(f"Mann-Whitney U (male vs female):      p = {stats.mannwhitneyu(m, f).pvalue:.4f}")
print(f"Kruskal-Wallis (three segments):      p = {stats.kruskal(*groups).pvalue:.2e}")
print("\nObserved counts (region x segment):\n" + obs.to_string())
print(f"\nCritical values: z (two-tailed, 95 pct) = {stats.norm.ppf(0.975):.2f} | t (df=199, two-tailed) = {stats.t.ppf(0.975, 199):.2f} | chi-square (df={dof}) = {stats.chi2.ppf(0.95, dof):.2f}")
Real output (captured when this page was built)
Data audit: (200, 8) | missing: 0 | duplicates: 0

Question                      Test                    H0                        p-value   Decision (alpha 0.05)
Q1 sample vs population       one-sample t            mean usage = 50           0.2434    Fail to reject H0
Q2 before vs after (month 1)  paired t, one-tailed    post <= pre               0.0498    Reject H0
Q2b before vs after (month 2) paired t, one-tailed    post <= pre               0.0000    Reject H0
Q3 male vs female             independent t (Welch)   mean_m = mean_f           0.9912    Fail to reject H0
Q4 three segments             one-way ANOVA           all segment means equal   0.1856    Fail to reject H0
Q5 segment vs region          chi-square (df=6)       independent               0.0001    Reject H0
Q6 Pearson r = 0.75           Pearson                 no linear correlation     0.0000    Reject H0
Q6b Spearman rho = 0.70       Spearman                no monotonic correlation  0.0000    Reject H0

Shapiro-Wilk on paired differences: p = 0.864 (looks normal)
Wilcoxon signed-rank (month 2 > pre): p = 1.49e-07
Mann-Whitney U (male vs female):      p = 0.7841
Kruskal-Wallis (three segments):      p = 1.63e-01

Observed counts (region x segment):
segment   1   2   3
region             
1        22  15  13
2        23  10   9
3         6  21  23
4        13  16  29

Critical values: z (two-tailed, 95 pct) = 1.96 | t (df=199, two-tailed) = 1.97 | chi-square (df=6) = 12.59

5. Reading the output

  • The data has 200 customers with usage before and in two months after a campaign, plus sex, region and segment, like the class case.
  • Q2 uses ttest_rel with alternative='greater' because the same customers are measured twice and we only care about an increase.
  • Q3 uses Welch's t-test (equal_var=False), the safe default when group variances may differ.
  • Q5 builds the observed table with pd.crosstab; chi2_contingency also returns the expected table and the degrees of freedom (r - 1) x (c - 1).
  • Month 1 is borderline (p = 0.0498): the honest report is "weak evidence, re-check with more data", not a celebration.
  • The last lines check normality and run the non-parametric versions, which agree with the parametric results here.

6. Common mistakes

MistakeDo this instead
Using an independent t-test on before/after dataSame customers measured twice is paired data: use ttest_rel.
Saying "we accept H0"Say "we fail to reject H0": absence of evidence is not evidence of absence.
Choosing one-tailed after seeing the dataDecide the direction before running the test, or you double your false-alarm rate.
Running many tests and reporting the one with p < 0.05Adjust for multiple comparisons (Bonferroni) or pre-register the main question.
Treating a tiny p-value as a big effectReport the effect size too (difference in means, correlation).

7. Assignment

Download a public dataset with a before/after or group design (for example a Kaggle A/B test file). Answer four questions with four different tests. For each, write H0, Ha, the test, alpha, the p-value and a one-line business decision.

8. Interview questions

How do you choose between a t-test, ANOVA and chi-square?

By the data: compare means of two groups with a t-test, three or more groups with ANOVA, and test association between two categorical variables with chi-square.

What does a p-value of 0.03 mean?

If there were truly no effect, data at least this extreme would appear about 3% of the time. With alpha 0.05 we reject the null hypothesis.

When would you use a paired t-test?

When the same units are measured twice, such as customers before and after a campaign.

What do you do if the data is not normal?

Use the non-parametric version (Wilcoxon, Mann-Whitney, Kruskal-Wallis) or rely on the Central Limit Theorem for large samples of means.

9. Go further

Refer & earn