Implement a percentile clipping min-max scaler in pandas
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement a `PercentileClipScaler` class with `fit`, `transform` and `fit_transform` methods. `fit` learns a lower and an upper percentile bound for each column of a pandas DataFrame. `transform` clips each value to its column's bounds, then scales it to `[0, 1]` with `(x - lo) / (hi - lo)`. The constructor takes the two percentiles, `lower=5.0` and `upper=95.0` by default.
Requirements:
- Store the bounds as `pd.Series` attributes `lower_` and `upper_`, indexed by column name. Compute them with linear-interpolation percentiles that ignore NaN.
- A constant column (`hi == lo`) maps every non-NaN value to `0.0`, never to NaN.
- NaN inputs stay NaN in the output.
- Return a `float64` DataFrame with the columns in fit order and the input's index, whatever the column order of the input.
- Do not mutate the input frames. `fit` returns `self`.
Example, with the default percentiles:
```python
train = pd.DataFrame({"a": np.arange(21.0), "b": [7.0] * 21})
s = PercentileClipScaler().fit(train) # lower_["a"]=1.0, upper_["a"]=19.0
s.transform(pd.DataFrame({"a": [-5.0, 5.5, 25.0], "b": [7.0, 8.0, 9.0]}))
# a b
# 0 0.00 0.0
# 1 0.25 0.0
# 2 1.00 0.0
```
Column `a` is clipped to `[1, 19]`, so `5.5` becomes `(5.5 - 1) / 18 = 0.25`. Column `b` was constant in training, so every value maps to `0.0`, including `8.0` and `9.0`.
```hint Watch the zero range
A constant column has `hi - lo == 0`, so plain division gives `0/0`. Handle that case before it turns into NaN, and remember which inputs were NaN to begin with.
```
### What a Strong Answer Covers
- Bounds learned only in `fit`, with NaN-aware linear percentiles, stored as Series keyed by column name
- Clipping before scaling, so every non-NaN output lands in `[0, 1]`
- Zero-range columns handled without a division by zero, while NaN inputs still come back as NaN
- The output contract: fit column order, the input's index, `float64` dtype, and an untouched input frame
- Edge cases such as a column that is entirely NaN at fit time or a transform frame that is missing a fitted column
### Follow-up Questions
- How would you make this a scikit-learn compatible transformer?
- Why should the bounds be fit on training data only?
- What should happen when a column is entirely NaN at fit time?
- How would you compute the bounds on a dataset too large to fit in memory?
Overview: Implement a scaler that learns per-column percentile bounds from a pandas DataFrame, clips values to them and rescales to the 0 to 1 range. It tests NaN-aware percentiles, handling of constant columns, preserving missing values and keeping training statistics separate from evaluation data.