Cramér's V for Categorical Association

easy
Unit 2 · Statistics II0/3 to milestone

Correlation doesn't work between categorical variables like country and plan. Cramér's V turns the chi-square statistic of their contingency table into a 0–1 strength of association:

V=χ2/nmin⁡(r−1,  c−1)V = \sqrt{\frac{\chi^2 / n}{\min(r - 1,\; c - 1)}}

Implement:

  • contingency(a, b): the table of counts as a 2-D NumPy array, with rows for the sorted unique values of a and columns for those of b
  • chi_square(table): ∑(O−E)2E\sum \frac{(O - E)^2}{E} with Eij=rowi⋅coljnE_{ij} = \frac{\text{row}_i \cdot \text{col}_j}{n}
  • cramers_v(a, b): 0.0 if either variable has a single category
  • association_matrix(df, columns): a symmetric DataFrame of pairwise V values (1.0 on the diagonal)
#statistics#categorical-data#feature-selection2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Cramér's V for Categorical Association · TechGradify