Rank DataFrame features by association with a binary target in pandas

Quick Overview

Implement a pandas function that ranks every column of a DataFrame by its association with a binary target, using absolute Pearson correlation for numeric columns and target-rate spread for categorical ones. It tests dtype dispatch, handling of constant and undefined scores, and building an exact, sorted output frame.

Rank DataFrame features by association with a binary target in pandas

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

Implement `feature_target_ranking(df, target)`. `df` is a pandas DataFrame and `target` is the name of a binary 0/1 column in it. The function ranks every other column by its association with the target, choosing the measure from the column's dtype, and returns a single sortable report. Both measures lie in `[0, 1]`, but they are not comparable with each other. The report must follow these rules: - A numeric column gets measure `'abs_pearson'`. Its score is the absolute Pearson correlation with `target`. - An `object` or `category` column gets measure `'rate_spread'`. Its score is the highest target rate minus the lowest target rate across its levels, where the target rate of a level is the mean of `target` over that level's rows. - A constant column, or a column whose score is undefined, gets score `numpy.nan` and still appears in the report. Every non-target column appears exactly once, and `target` never appears. - The report has exactly the columns `['feature', 'measure', 'score']`. `feature` and `measure` have dtype `object`, and `score` has dtype `float64`. - Rows are sorted by `score` descending with NaN last, then by `feature` ascending, and the index is reset with `reset_index(drop=True)`. The result is graded with `pandas.testing.assert_frame_equal`. For example, with this input and `target='churned'`: ```text churned support_tickets plan device country seats 0 1 basic ios US 5 0 2 basic web US 5 1 3 pro ios US 5 1 4 pro web US 5 ``` the expected report is: ```text feature measure score 0 plan rate_spread 1.000000 1 support_tickets abs_pearson 0.894427 2 device rate_spread 0.000000 3 country rate_spread NaN 4 seats abs_pearson NaN ``` ```hint Dispatch on dtype pandas has helpers in `pd.api.types` for asking whether a column is numeric. Decide early what a column of some other dtype should do, because every column has to appear exactly once. ``` ```hint Undefined cases List the ways each formula can fail to produce a meaningful number (no variance, too few levels, all values missing) and check what your code returns for each one. A formula that quietly returns 0 is not the same as an undefined score. ``` ### Constraints & Assumptions - `target` holds only 0 and 1 (integer or bool dtype) and has no missing values. - Column names are unique strings. - A column counts as numeric when `pd.api.types.is_numeric_dtype` is true for it, so bool columns are scored with `'abs_pearson'`. Any other non-numeric dtype, such as the pandas `string` dtype, is scored with `'rate_spread'` so that it still appears once. - Missing values inside a feature are skipped: Pearson uses only rows where both values are present, and a missing value does not form its own level. ### What a Strong Answer Covers - A dtype dispatch that sends every non-target column to exactly one measure, including bool columns and dtypes the rules do not name. - Correct computation of both scores, with missing values and unused categorical levels kept out of the target rates. - Which inputs make a score undefined (constant numeric column, single-level categorical, all-missing column) and why they must score NaN instead of 0. - An output frame that passes `assert_frame_equal`: column order, dtypes, the NaN-last sort with the name tiebreak, and a reset index. - Why the two measures cannot be compared directly even though both lie in `[0, 1]`. ### Follow-up Questions - How would you handle a numeric column with only a few distinct values, such as an encoded ordinal? - Why should you warn against comparing `abs_pearson` and `rate_spread` scores directly, and what would make the ranking fair across dtypes? - If the target were continuous instead of 0/1, which parts of the function would still hold and what would you change?

Overview: Implement a pandas function that ranks every column of a DataFrame by its association with a binary target, using absolute Pearson correlation for numeric columns and target-rate spread for categorical ones. It tests dtype dispatch, handling of constant and undefined scores, and building an exact, sorted output frame.

PracHub logo
General
Nov 25, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

Implement feature_target_ranking(df, target). df is a pandas DataFrame and target is the name of a binary 0/1 column in it. The function ranks every other column by its association with the target, choosing the measure from the column's dtype, and returns a single sortable report. Both measures lie in [0, 1], but they are not comparable with each other.

The report must follow these rules:

  • A numeric column gets measure 'abs_pearson' . Its score is the absolute Pearson correlation with target .
  • An object or category column gets measure 'rate_spread' . Its score is the highest target rate minus the lowest target rate across its levels, where the target rate of a level is the mean of target over that level's rows.
  • A constant column, or a column whose score is undefined, gets score numpy.nan and still appears in the report. Every non-target column appears exactly once, and target never appears.
  • The report has exactly the columns ['feature', 'measure', 'score'] . feature and measure have dtype object , and score has dtype float64 .
  • Rows are sorted by score descending with NaN last, then by feature ascending, and the index is reset with reset_index(drop=True) . The result is graded with pandas.testing.assert_frame_equal .

For example, with this input and target='churned':

churned  support_tickets  plan   device  country  seats
0        1                basic  ios     US       5
0        2                basic  web     US       5
1        3                pro    ios     US       5
1        4                pro    web     US       5

the expected report is:

   feature          measure      score
0  plan             rate_spread  1.000000
1  support_tickets  abs_pearson  0.894427
2  device           rate_spread  0.000000
3  country          rate_spread       NaN
4  seats            abs_pearson       NaN

Constraints & Assumptions

  • target holds only 0 and 1 (integer or bool dtype) and has no missing values.
  • Column names are unique strings.
  • A column counts as numeric when pd.api.types.is_numeric_dtype is true for it, so bool columns are scored with 'abs_pearson' . Any other non-numeric dtype, such as the pandas string dtype, is scored with 'rate_spread' so that it still appears once.
  • Missing values inside a feature are skipped: Pearson uses only rows where both values are present, and a missing value does not form its own level.

What a Strong Answer Covers Guidance

  • A dtype dispatch that sends every non-target column to exactly one measure, including bool columns and dtypes the rules do not name.
  • Correct computation of both scores, with missing values and unused categorical levels kept out of the target rates.
  • Which inputs make a score undefined (constant numeric column, single-level categorical, all-missing column) and why they must score NaN instead of 0.
  • An output frame that passes assert_frame_equal : column order, dtypes, the NaN-last sort with the name tiebreak, and a reset index.
  • Why the two measures cannot be compared directly even though both lie in [0, 1] .

Follow-up Questions Guidance

  • How would you handle a numeric column with only a few distinct values, such as an encoded ordinal?
  • Why should you warn against comparing abs_pearson and rate_spread scores directly, and what would make the ranking fair across dtypes?
  • If the target were continuous instead of 0/1, which parts of the function would still hold and what would you change?