Chi-Square Test (categorical association)
When to use
Section titled “When to use”Use the chi-square test of independence when you have:
- Two categorical variables
- Counts in a contingency table
Example questions:
- Is purchase (yes/no) associated with plan type (basic/pro)?
- Is churn associated with region?
Example
Section titled “Example”import pandas as pd
from scipy.stats import chi2_contingency
# Example contingency table
# rows: plan, columns: churn
ct = pd.DataFrame(
{
"churn_no": [80, 120],
"churn_yes": [20, 60],
},
index=["basic", "pro"],
)
chi2, p, dof, expected = chi2_contingency(ct)
print("chi2:", chi2)
print("p:", p)
print("dof:", dof)
print("expected:\n", expected)Interpreting results
Section titled “Interpreting results”- Small p-value → evidence of association
- Expected counts should not be too small (rule of thumb: mostly >= 5)
Effect size (optional)
Section titled “Effect size (optional)”After significance, consider effect size like Cramér’s V.
How the test works
Section titled “How the test works”flowchart LR A["Contingency table
(observed counts)"] --> B["Expected counts
if variables were independent"] B --> C["Chi-square statistic
sum of (obs - exp)^2 / exp"] C --> D["p-value"] D --> E["Small p -> variables
are associated"]
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Build a contingency table
Section titled “Exercise 1 – Build a contingency table”Exercise 2 – Run the chi-square test
Section titled “Exercise 2 – Run the chi-square test”Exercise 3 – Checking expected counts
Section titled “Exercise 3 – Checking expected counts”Continue to Correlation vs Causation to measure how two numeric variables relate.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading