Cramér's V Feature Ranking

Quick Overview

Write a pandas and numpy function that ranks categorical features by their Cramér's V association with a categorical target, computing chi-squared by hand from each contingency table. It tests degenerate-case handling and exact output formatting for a strict DataFrame comparison.

Cramér's V Feature Ranking

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

Write `cramers_v_ranking(df, target)` that ranks categorical features by Cramér's V against the categorical `target` column, using `pandas` and `numpy` only. Requirements: - Candidates are the `object` and `category` columns other than `target`. Build each contingency table with `pd.crosstab`. - Compute `E = outer(row_totals, col_totals) / n`, `chi2 = sum((O - E)**2 / E)` and `V = sqrt((chi2 / n) / min(r - 1, k - 1))`, where `n` is the table total and `r`, `k` are its numbers of rows and columns. This is the uncorrected V, which lies in `[0, 1]`. - For a single-level feature (`min(r - 1, k - 1) == 0`), report `numpy` NaN. Do not raise `ZeroDivisionError`. - Do not call `scipy.stats.chi2_contingency` and do not return a p-value. - Return exactly the columns `['feature', 'cramers_v']` with dtypes `object` and `float64`, sorted by `cramers_v` descending, then `feature` ascending, with NaN scores last, followed by `reset_index(drop=True)`. The result is graded with `assert_frame_equal`, so column names, dtypes, row order and the index must all match. ```hint Expected counts Every cell of `E` must be positive before you divide by it. Think about which inputs can leave a row or column of a crosstab with a total of zero. ``` ```hint The exact frame `assert_frame_equal` also checks dtypes and the index. Decide what the function returns when no column qualifies, and check that ties in the score come out in alphabetical order. ``` ### Constraints & Assumptions - Only `pandas` and `numpy` are available. - `pd.crosstab` drops rows where the feature or the target is missing, so `n` is the number of complete pairs for that feature and can differ from feature to feature. - `target` may itself be an `object` or `category` column; it is never a candidate. ### What a Strong Answer Covers - Builds each table with `pd.crosstab` and computes `E`, chi-squared and V by hand exactly as specified. - Returns NaN for the degenerate cases (a single observed level in the feature or the target, unused categorical levels, no complete rows) without raising or producing `inf`. - Returns the required columns, dtypes, sort order and a fresh `RangeIndex`, including the case where no column qualifies. - States the time and space cost in terms of rows, candidate columns and table size. - Explains what V measures and where it misleads as a ranking score. ### Follow-up Questions - How would you add the bias-corrected Cramér's V (Bergsma correction)? - Why can Cramér's V be misleading for high-cardinality columns? - Cramér's V is symmetric. When would an asymmetric measure such as Theil's U rank features better?

Overview: Write a pandas and numpy function that ranks categorical features by their Cramér's V association with a categorical target, computing chi-squared by hand from each contingency table. It tests degenerate-case handling and exact output formatting for a strict DataFrame comparison.

Nov 24, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

Write cramers_v_ranking(df, target) that ranks categorical features by Cramér's V against the categorical target column, using pandas and numpy only.

Requirements:

  • Candidates are the object and category columns other than target . Build each contingency table with pd.crosstab .
  • Compute E = outer(row_totals, col_totals) / n , chi2 = sum((O - E)**2 / E) and V = sqrt((chi2 / n) / min(r - 1, k - 1)) , where n is the table total and r , k are its numbers of rows and columns. This is the uncorrected V, which lies in [0, 1] .
  • For a single-level feature ( min(r - 1, k - 1) == 0 ), report numpy NaN. Do not raise ZeroDivisionError .
  • Do not call scipy.stats.chi2_contingency and do not return a p-value.
  • Return exactly the columns ['feature', 'cramers_v'] with dtypes object and float64 , sorted by cramers_v descending, then feature ascending, with NaN scores last, followed by reset_index(drop=True) .

The result is graded with assert_frame_equal, so column names, dtypes, row order and the index must all match.

Constraints & Assumptions

  • Only pandas and numpy are available.
  • pd.crosstab drops rows where the feature or the target is missing, so n is the number of complete pairs for that feature and can differ from feature to feature.
  • target may itself be an object or category column; it is never a candidate.

What a Strong Answer Covers Guidance

  • Builds each table with pd.crosstab and computes E , chi-squared and V by hand exactly as specified.
  • Returns NaN for the degenerate cases (a single observed level in the feature or the target, unused categorical levels, no complete rows) without raising or producing inf .
  • Returns the required columns, dtypes, sort order and a fresh RangeIndex , including the case where no column qualifies.
  • States the time and space cost in terms of rows, candidate columns and table size.
  • Explains what V measures and where it misleads as a ranking score.

Follow-up Questions Guidance

  • How would you add the bias-corrected Cramér's V (Bergsma correction)?
  • Why can Cramér's V be misleading for high-cardinality columns?
  • Cramér's V is symmetric. When would an asymmetric measure such as Theil's U rank features better?