Cap a pandas column at its upper quantile (one-sided winsorization)
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `cap_upper_quantile(df: pd.DataFrame, col: str, q: float) -> pd.Series` that winsorizes `df[col]` at its upper tail only. Values above the `q`-quantile of the column are clipped down to that quantile, and every other value is left as it is.
Requirements:
- Compute the cap as the `q`-quantile of `df[col]` with linear interpolation between order statistics (the pandas default, `interpolation='linear'`).
- Replace every value above the cap with the cap.
- Do not clip the lower tail and do not drop rows. The output has the same length as the input.
- Return a `pd.Series` that keeps the original index.
Example:
```python
df = pd.DataFrame({"x": [1, 2, 3, 4, 100]})
cap_upper_quantile(df, "x", 0.9)
# cap = 61.6 (the 0.9-quantile), so 100 becomes 61.6
# 0 1.0
# 1 2.0
# 2 3.0
# 3 4.0
# 4 61.6
```
```hint Check the cap by hand
With five sorted values, the 0.9-quantile sits at position (n - 1) * q = 3.6, between the fourth and fifth values. Work out the cap yourself before you trust a library call.
```
```hint Watch the shape and the dtype
Filtering rows or building a plain list loses rows or the index. Look for a vectorized operation that bounds values on one side only, and check what happens to an integer column when the cap is fractional.
```
### Constraints & Assumptions
- `df[col]` holds numbers (integers or floats).
- `q` is between 0 and 1 inclusive.
- Results are compared with a floating-point tolerance, since the cap is usually fractional.
### What a Strong Answer Covers
- How the cap is computed, including the interpolation rule, with the example's cap checked by hand.
- Bounding only the upper tail while keeping every row, the index, and the values at or below the cap.
- What the output dtype becomes for an integer column with a fractional cap.
- Edge cases: missing values, an empty column, and the extreme values of `q`.
- Time and space complexity.
### Follow-up Questions
- How would you extend this to two-sided capping at `q` and `1 - q`?
- What happens if `col` contains NaN values, and what should happen?
- You fit this cap on training data. How do you apply it to validation data or to live traffic?
- When is capping a worse choice than dropping the outliers or transforming the column, for example with a log?
Overview: Implement one-sided winsorization in pandas: cap a numeric column at its upper q-quantile while keeping every row and the original index. It tests how quantiles are interpolated, how to bound values without dropping rows, and how dtype and missing values behave.