Rank numeric column pairs by the gap between Spearman and Pearson correlation

Quick Overview

Write a pandas function that computes Pearson and Spearman correlations for every pair of numeric columns and ranks the pairs by the gap between them. It tests the difference between linear and monotonic association, handling of NaN and constant columns, and an exact DataFrame output contract with deterministic sorting.

Rank numeric column pairs by the gap between Spearman and Pearson correlation

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

Implement `pearson_vs_spearman_gap(df)`. For every unordered pair of distinct numeric columns in a pandas DataFrame, compute the Pearson and Spearman correlations and the gap between them, so that relationships which are monotonic but not linear stand out. The result must meet these requirements: - Numeric columns only. Each unordered pair appears once, with `col_a` set to the column that comes first in the DataFrame's column order. - Columns exactly `['col_a', 'col_b', 'pearson', 'spearman', 'gap']`. - Dtypes `object, object, float64, float64, float64`. - `gap = abs(spearman) - abs(pearson)`. - Sort by `gap` descending, then `col_a`, then `col_b` ascending, then `reset_index(drop=True)`. Example, where `cube` is `x**3` (monotonic but not linear), `noise` is a shuffled sequence with little relation to either, and `label` is text: ```python df = pd.DataFrame({ 'x': [1, 2, 3, 4, 5], 'cube': [1, 8, 27, 64, 125], 'noise': [2, 5, 1, 4, 3], 'label': ['a', 'b', 'c', 'd', 'e'], }) out = pearson_vs_spearman_gap(df) ``` Expected result, with values rounded to four decimals: ```text col_a col_b pearson spearman gap 0 x cube 0.9431 1.0000 0.0569 1 cube noise 0.0776 0.1000 0.0224 2 x noise 0.1000 0.1000 0.0000 ``` The pair `('x', 'cube')` has a Spearman correlation of exactly 1 but a lower Pearson correlation, so it has the largest gap and ranks first. `label` is not numeric and never enters a pair. ```hint Compute once, look up per pair pandas can build a full correlation matrix for each method in one call, so the loop over pairs only has to read values out of two matrices. ``` ```hint Watch the ordering Check that each pair appears exactly once and that the three sort keys fully determine the row order, including when a correlation comes back as NaN. ``` ### Constraints & Assumptions - The input is a pandas DataFrame with n rows and k columns of mixed dtypes. Only integer and float columns count as numeric (`select_dtypes(include='number')`), so text and boolean columns are skipped. - With fewer than two numeric columns there are no pairs, and the result is an empty DataFrame with the five columns and dtypes above. - Spearman uses average ranks for ties, the default in pandas and SciPy. ### What a Strong Answer Covers - Why the two coefficients differ: Pearson measures linear association and Spearman is Pearson computed on ranks. - Why the gap compares absolute values, and what a large positive gap says about the shape of the relationship. - The exact output contract: column names, dtypes, one row per unordered pair in column order, the three-key sort and the reset index. - Behavior on non-numeric columns, missing values, constant columns and inputs with fewer than two numeric columns. - Cost in terms of the number of numeric columns and rows. ### Follow-up Questions - How would you handle columns with NaNs or near-zero variance? - How would you attach a significance or confidence signal to each gap? - Some pairs come back with a large negative gap, meaning Pearson is stronger than Spearman in absolute value. What kind of data produces that?

Overview: Write a pandas function that computes Pearson and Spearman correlations for every pair of numeric columns and ranks the pairs by the gap between them. It tests the difference between linear and monotonic association, handling of NaN and constant columns, and an exact DataFrame output contract with deterministic sorting.

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

Implement pearson_vs_spearman_gap(df). For every unordered pair of distinct numeric columns in a pandas DataFrame, compute the Pearson and Spearman correlations and the gap between them, so that relationships which are monotonic but not linear stand out.

The result must meet these requirements:

  • Numeric columns only. Each unordered pair appears once, with col_a set to the column that comes first in the DataFrame's column order.
  • Columns exactly ['col_a', 'col_b', 'pearson', 'spearman', 'gap'] .
  • Dtypes object, object, float64, float64, float64 .
  • gap = abs(spearman) - abs(pearson) .
  • Sort by gap descending, then col_a , then col_b ascending, then reset_index(drop=True) .

Example, where cube is x**3 (monotonic but not linear), noise is a shuffled sequence with little relation to either, and label is text:

df = pd.DataFrame({
    'x': [1, 2, 3, 4, 5],
    'cube': [1, 8, 27, 64, 125],
    'noise': [2, 5, 1, 4, 3],
    'label': ['a', 'b', 'c', 'd', 'e'],
})
out = pearson_vs_spearman_gap(df)

Expected result, with values rounded to four decimals:

  col_a  col_b  pearson  spearman     gap
0     x   cube   0.9431    1.0000  0.0569
1  cube  noise   0.0776    0.1000  0.0224
2     x  noise   0.1000    0.1000  0.0000

The pair ('x', 'cube') has a Spearman correlation of exactly 1 but a lower Pearson correlation, so it has the largest gap and ranks first. label is not numeric and never enters a pair.

Constraints & Assumptions

  • The input is a pandas DataFrame with n rows and k columns of mixed dtypes. Only integer and float columns count as numeric ( select_dtypes(include='number') ), so text and boolean columns are skipped.
  • With fewer than two numeric columns there are no pairs, and the result is an empty DataFrame with the five columns and dtypes above.
  • Spearman uses average ranks for ties, the default in pandas and SciPy.

What a Strong Answer Covers Guidance

  • Why the two coefficients differ: Pearson measures linear association and Spearman is Pearson computed on ranks.
  • Why the gap compares absolute values, and what a large positive gap says about the shape of the relationship.
  • The exact output contract: column names, dtypes, one row per unordered pair in column order, the three-key sort and the reset index.
  • Behavior on non-numeric columns, missing values, constant columns and inputs with fewer than two numeric columns.
  • Cost in terms of the number of numeric columns and rows.

Follow-up Questions Guidance

  • How would you handle columns with NaNs or near-zero variance?
  • How would you attach a significance or confidence signal to each gap?
  • Some pairs come back with a large negative gap, meaning Pearson is stronger than Spearman in absolute value. What kind of data produces that?