Clip a Pandas Column to Bounds and Flag the Rows That Changed
Quick Overview
Write a pandas function that clips a numeric column to lower and upper bounds and adds a boolean column marking which rows changed, without mutating the input. It tests vectorized clip, element-wise comparison, column order, index preservation and how missing values affect the flag.
Clip a Pandas Column to Bounds and Flag the Rows That Changed
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `def clip_and_flag(df: pd.DataFrame, lo: float, hi: float) -> pd.DataFrame`. Given `df` with numeric column `'x'`, return a copy with `'x_clipped'` and a boolean `'was_clipped'` column added.
Requirements:
- Do not mutate the input: operate on `df.copy()`.
- `'x_clipped'` = `df['x'].clip(lower=lo, upper=hi)`.
- `'was_clipped'` = `df['x'] != df['x_clipped']` (boolean dtype).
- Column order: `'x'`, `'x_clipped'`, `'was_clipped'`.
- Preserve the original index.
Example:
```python
df = pd.DataFrame({'x': [-1.0, 2.0, 5.0, 10.0]})
clip_and_flag(df, lo=0.0, hi=6.0)
# x x_clipped was_clipped
# 0 -1.0 0.0 True
# 1 2.0 2.0 False
# 2 5.0 5.0 False
# 3 10.0 6.0 True
```
```hint Avoid side effects
Assigning a new column to the DataFrame you received changes the caller's object. Decide where the new columns get written before you add them.
```
### Constraints & Assumptions
- `lo <= hi`, and `'x'` is numeric.
- No other columns need to be preserved in the output.
- The index can hold any labels, and the output must keep it unchanged.
### What a Strong Answer Covers
- Where the new columns are written, and why the caller's DataFrame stays unchanged.
- A vectorized clip that applies both bounds in one call.
- How the flag is derived, and why it is True exactly where a bound was applied.
- The required column order and the original index in the returned frame.
- How missing values in `'x'` interact with the flag.
### Follow-up Questions
- How would you handle `NaN` values in `'x'`?
- How would you generalize this to clip multiple numeric columns at once?
- Do the comparison flag and a direct `(x < lo) | (x > hi)` check ever disagree?
- How would you pick `lo` and `hi` from the data for a model feature?
Overview: Write a pandas function that clips a numeric column to lower and upper bounds and adds a boolean column marking which rows changed, without mutating the input. It tests vectorized clip, element-wise comparison, column order, index preservation and how missing values affect the flag.
Implement def clip_and_flag(df: pd.DataFrame, lo: float, hi: float) -> pd.DataFrame. Given df with numeric column 'x', return a copy with 'x_clipped' and a boolean 'was_clipped' column added.