typestar

Categorical association in Python

A contingency table, a chi-square test, and Fisher's exact for small counts.

import numpy as np
from scipy import stats

table = np.array([[30, 10], [18, 22]])

result = stats.chi2_contingency(table)
print(round(result.statistic, 3), f"{result.pvalue:.5f}", result.dof)
print(result.expected_freq.round(1))

small = np.array([[8, 2], [1, 5]])
odds, p = stats.fisher_exact(small)
print(round(odds, 3), round(p, 5))

How it works

  1. chi2_contingency returns the statistic, p, dof and expected counts.
  2. The expected table is what the test compares against.
  3. fisher_exact is right when any expected count is tiny.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
336
Tokens
119
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 68 seconds.

Type this snippet

Step 3 of 4 in Hypothesis tests, step 6 of 23 in Scientific computing with SciPy.

← Previous Next →