Replace negative values with zero in a pandas Series using Series.where
Quick Overview
Write a pandas function that returns a copy of a numeric Series with every negative value replaced by zero, using Series.where. It tests the keep-condition semantics of where, handling of missing values, and preserving the index and dtype without mutating the input.
Replace negative values with zero in a pandas Series using Series.where
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `floor_negatives(s: pd.Series) -> pd.Series` that returns a copy of the numeric Series `s` with every negative value replaced by `0`.
Requirements:
- Replace values `< 0` with `0` and keep values `>= 0` unchanged.
- Use `Series.where`. Do not use `clip`, `mask` or boolean assignment.
- Do not mutate the input: return a new Series.
- Preserve the original index.
- Keep a numeric dtype: `float` input stays `float`.
For example:
```python
s = pd.Series([-3.0, 2.0, -1.5, 0.0, 4.0])
floor_negatives(s)
# 0 0.0
# 1 2.0
# 2 0.0
# 3 0.0
# 4 4.0
# dtype: float64
```
```hint Which positions does where keep?
`Series.where` keeps a value where its condition is True and replaces it where the condition is False. Write the condition for the values you want to keep, then check what it evaluates to for a missing value.
```
### What a Strong Answer Covers
- A `where` call whose condition describes the values to keep, with `0` as the replacement.
- How the chosen condition treats `NaN`, and whether missing values survive.
- Why the input is not mutated and the index is preserved.
- Why the dtype stays `float64` for float input and `int64` for integer input.
### Follow-up Questions
- How does `Series.where` differ from `Series.mask`?
- When can `where` change the dtype of an integer Series?
- How would you floor negatives in every numeric column of a DataFrame while leaving text columns alone?
Overview: Write a pandas function that returns a copy of a numeric Series with every negative value replaced by zero, using Series.where. It tests the keep-condition semantics of where, handling of missing values, and preserving the index and dtype without mutating the input.