Find the Most Strongly Correlated Pair of Numeric Columns in a DataFrame
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `strongest_pair(df)` that returns a tuple `(col_a, col_b, r)` for the pair of distinct numeric columns with the largest absolute Pearson correlation. `col_a` and `col_b` are `str`, and `r` is the signed correlation as a `float`.
The function must follow these rules:
- Ignore non-numeric columns. Never return a self-pair, and consider each pair only once, not in both orders.
- Choose the pair by the largest `|r|`, but return the signed `r`.
- `col_a` must appear before `col_b` in `df.columns`.
- On ties in `|r|`, return the pair whose `(col_a, col_b)` tuple comes first alphabetically.
```python
df = pd.DataFrame({
"a": [1, 2, 3, 4],
"b": [2, 4, 6, 8], # perfectly correlated with a
"c": [9, 1, 6, 2],
})
strongest_pair(df)
# -> ("a", "b", 1.0)
```
`b` is exactly twice `a`, so their correlation is 1.0, while `c` correlates at about -0.56 with both of them.
```python
df = pd.DataFrame({
"m": [1, 2, 3, 4],
"b": [4, 3, 2, 1],
"k": [2, 4, 6, 8],
})
strongest_pair(df)
# -> ("b", "k", -1.0)
```
All three pairs have `|r| = 1`. In column order the candidates are `("m", "b")`, `("m", "k")` and `("b", "k")`, and `("b", "k")` comes first alphabetically. Its correlation is negative because `b` falls as `k` rises.
```hint Visit each pair once
The correlation matrix is symmetric and its diagonal compares each column with itself. Choose loop bounds, or a mask, that touch every distinct pair exactly once in column order.
```
### Clarifying Questions to Ask
- What should the function return when there are fewer than two numeric columns, or when no pair has a defined correlation?
- Do boolean columns count as numeric?
### What a Strong Answer Covers
- Restricting to numeric columns and computing the Pearson correlations once.
- Visiting each unordered pair once, with no self-pairs and with `col_a` earlier in `df.columns`.
- Selecting on `|r|` while returning the signed value.
- A deterministic alphabetical tie-break.
- NaN correlations and frames with too few numeric columns.
### Follow-up Questions
- How would you handle columns that produce NaN correlations, such as a constant column?
- How would this scale to a DataFrame with thousands of columns?
- When would Spearman correlation be a better choice than Pearson for this search?
Overview: Write a pandas function that finds the pair of distinct numeric columns with the largest absolute Pearson correlation and returns the signed value. It tests working with a correlation matrix, visiting each pair once, deterministic tie-breaking, and handling constant columns that produce NaN.