Winsorize a Numeric Pandas Series to Fixed Bounds With clip
Quick Overview
Write a pandas function that caps a numeric Series to fixed lower and upper bounds while keeping missing values, the index and the dtype unchanged. It tests vectorized clipping, NaN handling, avoiding mutation, and how to extend the idea to percentile-based winsorizing.
Winsorize a Numeric Pandas Series to Fixed Bounds With clip
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `clip_outliers(s, lower, upper)` that winsorizes a numeric Series: values below `lower` become `lower`, values above `upper` become `upper`, and in-range values are unchanged. Return a new Series without mutating the input.
The function must meet these requirements:
- Clamp values to the closed range `[lower, upper]`.
- `NaN` stays `NaN` (no filling).
- Preserve the index, the order and the `float64` dtype.
Example:
```python
clip_outliers(pd.Series([-5.0, 3.0, 50.0]), 0.0, 10.0)
# -> pd.Series([0.0, 3.0, 10.0])
```
```hint Missing values
Think about what a hand-written comparison such as `s >= lower` returns for a `NaN` entry, and what that would do to the missing values.
```
### What a Strong Answer Covers
- A vectorized bound on both sides that returns a new Series and leaves the input untouched.
- How missing values stay `NaN`, and why a hand-rolled comparison can break that.
- The index, order and dtype of the result.
- The time and space cost.
### Follow-up Questions
- How would you winsorize by percentile instead of fixed bounds?
- What if `lower > upper`?
- How would you apply percentile bounds learned on training data to new data?
Overview: Write a pandas function that caps a numeric Series to fixed lower and upper bounds while keeping missing values, the index and the dtype unchanged. It tests vectorized clipping, NaN handling, avoiding mutation, and how to extend the idea to percentile-based winsorizing.
Implement clip_outliers(s, lower, upper) that winsorizes a numeric Series: values below lower become lower, values above upper become upper, and in-range values are unchanged. Return a new Series without mutating the input.
The function must meet these requirements:
Clamp values to the closed range
[lower, upper]
.
NaN
stays
NaN
(no filling).
Preserve the index, the order and the
float64
dtype.