Winsorize a NumPy Array to Fixed Bounds with np.clip
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `winsorize(a, lo, hi)`: values below `lo` become `lo`, values above `hi` become `hi`.
- Use `np.clip(a, lo, hi)`.
- Preserve the input's shape and dtype behavior.
- Return a new array without mutating the input.
For example:
```python
a = np.array([-2.0, 0.5, 3.0, 8.0])
winsorize(a, lo=0.0, hi=5.0)
# array([0. , 0.5, 3. , 5. ])
```
```hint Inputs np.clip does not check
Look up what `np.clip` does when `lo` is greater than `hi`, and when the array contains NaN.
```
### What a Strong Answer Covers
- What happens to values below, inside and above the range `[lo, hi]`.
- A vectorized implementation that returns a new array and leaves the input unchanged.
- The shape and dtype of the result, including integer input and float bounds.
- Handling of unusual input such as `lo > hi`, NaN values and empty arrays.
### Follow-up Questions
- How would you winsorize at the 5th and 95th percentiles of the data instead of at fixed bounds?
- How would you winsorize each column of a 2-D array with its own bounds?
- When is winsorizing a feature a good idea, and when would you drop or transform the outliers instead?
- How would you do this in place to save memory, and what is the risk?
Overview: Implement a NumPy function that winsorizes an array by capping values below a lower bound and above an upper bound. It tests vectorized clipping, keeping the input unchanged, dtype behavior and how to handle edge cases such as swapped bounds and NaN values.