Winsorize a column within each group at its 5th and 95th percentiles in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `winsorize_by_group(df, group_col, value_col)` that clips outliers in `value_col` to percentile bounds computed independently within each group of `group_col`. Values are clipped, not dropped.
Requirements:
- Per group, compute `lo = quantile(0.05)` and `hi = quantile(0.95)` with `interpolation='linear'`.
- Clip each group's values to its own `[lo, hi]`.
- Return a new `pd.Series` aligned to the original index: no rows dropped or reordered.
- A single-row group is unchanged (`lo == hi`).
- Do not mutate the input `df`.
Example:
```python
df = pd.DataFrame({
"g": ["a", "a", "a", "b", "b"],
"v": [1.0, 100.0, 50.0, 5.0, 500.0],
})
out = winsorize_by_group(df, "g", "v")
# 0 5.90
# 1 95.00
# 2 50.00
# 3 29.75
# 4 475.25
# Name: v, dtype: float64
```
```hint Keep one output per row
You need a per-group computation whose result lines up row for row with the input. Look for a groupby method that returns something the same length as the original column.
```
```hint Check the quantile by hand
With linear interpolation, the $p$-th quantile of a sorted group of $n$ values sits at position $p(n-1)$. Work out the bounds for group `b` and see how far its two values move.
```
### What a Strong Answer Covers
- How the per-group bounds are computed and mapped back to every row without dropping or reordering anything
- How linear interpolation produces the bounds in the example
- What happens to single-row and very small groups, to `NaN` values, and to rows with a missing group key
- How the function avoids mutating `df`, and what it costs when there are many groups
### Follow-up Questions
- How would you make the percentile bounds configurable per call?
- How would you vectorize this to avoid a Python-level loop over groups?
- What if a group contains `NaN` values in `value_col`?
- When is per-group winsorization a poor choice, for example for groups with only a few rows?
Overview: Write a pandas function that winsorizes a value column within each group, clipping values to that group's own 5th and 95th percentiles while keeping every row in its original order. It tests groupby transform, linear quantile interpolation, small groups and missing values, and how to vectorize per-group work.