Chapter 81 · Solutions
Choosing the Test — Worked Solutions ✅
Five challenges, each verified in code.
⚙️ Setup¶
In [1]:
import numpy as np, pandas as pd
from scipy import stats
BASE="https://raw.githubusercontent.com/johnfisher-ai/Statistics-Data-Science-AI-Visual-Book/main/data/"
rng=np.random.default_rng(810)
try: d = pd.read_excel("../../data/choosing-the-right-test--clinic_visits.xlsx", sheet_name="Visits")
except FileNotFoundError: d = pd.read_excel(BASE+"choosing-the-right-test--clinic_visits.xlsx", sheet_name="Visits")
CHALLENGE 1
Name the test
Outcome = numeric, 2 paired groups, roughly normal. Which test? Then run it on BP before/after.
In [2]:
print("paired t-test")
print(f"p={stats.ttest_rel(d.sysbp_after,d.sysbp_before).pvalue:.2e}")
paired t-test p=3.68e-48
CHALLENGE 2
Name the test
Outcome = numeric, 2 independent groups. Which test? Run it on BP drop by treatment.
In [3]:
drop=d.sysbp_before-d.sysbp_after
print("two-sample (Welch) t-test")
print(f"p={stats.ttest_ind(drop[d.treatment=="new"],drop[d.treatment=="standard"],equal_var=False).pvalue:.2e}")
two-sample (Welch) t-test p=1.49e-09
CHALLENGE 3
Name the test
Two categorical variables. Which test? Run it on treatment x satisfied.
In [4]:
print("chi-square test of independence")
print(f"p={stats.chi2_contingency(pd.crosstab(d.treatment,d.satisfied))[1]:.3f}")
chi-square test of independence p=0.269
CHALLENGE 4
Name the test
Numeric outcome, 3 groups, but heavily skewed. Which test? Run it on wait_minutes by clinic.
In [5]:
print("Kruskal-Wallis (skewed -> nonparametric ANOVA)")
g=[x.wait_minutes.values for _,x in d.groupby("clinic")]
print(f"p={stats.kruskal(*g).pvalue:.3f}")
Kruskal-Wallis (skewed -> nonparametric ANOVA) p=0.333
CHALLENGE 5
One proportion vs a target
Is the overall satisfaction rate different from 0.70? Pick and run the test.
In [6]:
s=d.satisfied; n=len(s); ph=s.mean(); p0=0.70; z=(ph-p0)/np.sqrt(p0*(1-p0)/n)
print(f"one-proportion z-test: phat={ph:.3f}, z={z:.2f}, p={2*(1-stats.norm.cdf(abs(z))):.3f}")
one-proportion z-test: phat=0.685, z=-0.46, p=0.643
Statistics, Data Science and AI: A Visual Handbook · © 2026 John Fisher