Python Central HubSign in

Data Analytics with Python / Phase 8: Statistics for Data Analytics

Chi-Square Test (categorical association)

Test association between categorical variables using contingency tables and the chi-square test.

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

Python
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

  • Small p-value → evidence of association
  • Expected counts should not be too small (rule of thumb: mostly >= 5)

Effect size (optional)

After significance, consider effect size like Cramér’s V.

How the test works

diagram Chi-square test of independence mermaid
Observed counts are compared against the counts you'd expect if the two variables were unrelated.

Check your understanding

quizCheck yourself
  1. When do you use the chi-square test of independence?

    Show answer

    A — Two categorical variables with counts in a contingency table — The test works on counts cross-tabulated by two categorical variables, such as plan and churn.

  2. Which function runs the test in the lesson?

    Show answer

    A — chi2_contingency — chi2_contingency(ct) returns chi2, p, dof and the expected counts.

  3. The plan by churn table has 2 rows and 2 columns. How many degrees of freedom?

    Show answer

    C — 1 — dof = (rows - 1) times (columns - 1) = 1 times 1 = 1.

  4. What rule of thumb applies to expected counts?

    Show answer

    B — They should mostly be 5 or more — If expected counts are too small the chi-square approximation becomes unreliable.

🧪 Try It Yourself

Exercise 1 – Build a contingency table

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 – Run the chi-square test

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 – Checking expected counts

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Next

Continue to Correlation vs Causation to measure how two numeric variables relate.

Was this page helpful?

Let us know how we did