Rank numeric features by their Pearson correlation with a target column in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `correlation_with_target(df, target)` that returns a `pd.Series` of the signed Pearson correlation between every other numeric column and the numeric `target` column.
- Ignore non-numeric columns and exclude `target` itself.
- Index: feature names (dtype object, named `feature`). Values: the signed r as `float64`.
- Sort by absolute r descending, with ties broken by feature name ascending. Keep the feature names as the index; do not reset it.
- Name the Series `r`.
For example, with `price` (in thousands) as the target and a text column `city`:
```python
df = pd.DataFrame({
"price": [100, 200, 300, 400, 500],
"size": [1000, 1400, 1200, 1800, 1600],
"age": [40, 30, 20, 10, 20],
"rooms": [2, 4, 3, 2, 4],
"city": ["Austin", "Boston", "Austin", "Denver", "Boston"],
})
correlation_with_target(df, "price")
```
```text
feature
age -0.832050
size 0.800000
rooms 0.316228
Name: r, dtype: float64
```
`city` is excluded because it is not numeric, and `price` is excluded because it is the target. `age` comes first because its correlation has the largest magnitude, even though it is negative.
```hint Scope the computation
Building the full correlation matrix and reading one column works, but it does far more work than needed. Think about correlating each column with a single Series.
```
### Constraints & Assumptions
- `target` is a numeric column of `df`.
- Numeric columns are the ones `select_dtypes(include="number")` returns, so boolean columns are left out.
- Each feature's r uses the rows where both the feature and the target are non-null.
### What a Strong Answer Covers
- Selecting the numeric columns and excluding the target before ranking.
- One vectorized correlation per feature, and the cost difference from computing the full correlation matrix.
- The exact output contract: signed `float64` values, an object index named `feature`, the Series name `r`, and the two-key sort.
- What happens with constant columns and with missing values.
### Follow-up Questions
- How would you handle a feature that is constant (zero variance)?
- How would you extend this to rank by a non-linear association instead of Pearson?
- What can go wrong if you use this ranking to choose features for a model?
Overview: Write a pandas function that computes the signed Pearson correlation of every numeric feature with a target column and ranks the features by absolute correlation. It tests column selection, vectorized correlation, a two-key sort and an exact Series output for exploratory analysis.