Compute Spearman rank correlation as the Pearson correlation of average ranks
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `rank_correlation_matrix(df)`: select the numeric columns, replace each by its ranks (ties get the average rank), and return the Pearson correlation matrix of those ranks. Do not call `.corr(method='spearman')`.
Requirements:
- Use only numeric columns, preserving their original order.
- Rank with average ties (for example `Series.rank(method='average')`).
- Return a square `float64` `pd.DataFrame` indexed and columned by the numeric column names, symmetric with a `1.0` diagonal.
- The result must equal `df.corr(method='spearman', numeric_only=True)` to floating tolerance.
Example:
```python
df = pd.DataFrame({
"x": [1, 2, 3, 4, 100], # outlier
"y": [10, 20, 30, 40, 50],
})
rank_correlation_matrix(df)
# x y
# x 1.0 1.0 # perfectly monotonic despite the outlier
# y 1.0 1.0
```
```hint Whole-frame operations
pandas can rank every column at once and build the full correlation matrix in one call. Look at `DataFrame.rank` and `DataFrame.corr` before writing any loops.
```
```hint Testing against pandas
When you compare with `df.corr(method='spearman', numeric_only=True)`, use a column that contains a tied value. The tie rule is where from-scratch versions usually drift.
```
### Clarifying Questions to Ask
- Can columns contain missing values, and must the result still match pandas in that case?
- Do boolean columns count as numeric for this report?
- What should a constant column produce, given that its rank variance is zero?
### What a Strong Answer Covers
- Numeric column selection that keeps the original column order.
- Average ranks for ties, and why a different tie rule changes the result.
- Pearson correlation on the ranks, returned as a labeled, square `float64` matrix.
- When the result matches pandas' Spearman output exactly and where it can differ.
- Time and space cost in terms of rows and columns.
### Follow-up Questions
- Why does Pearson on ranks equal the classic `1 - 6Σd²/(n(n²-1))` formula, and when does that formula give the wrong answer?
- How would you handle NaNs in a column?
- When would you prefer Kendall's tau to Spearman's rho?
Overview: Implement a Spearman correlation matrix in pandas by ranking each numeric column with average ties and correlating the ranks, without calling the built-in spearman method. It tests rank correlation, tie handling, column selection and how missing values change the result.