Write a pandas function that forward fills missing values in a Series with the most recent preceding valid value while leaving leading gaps alone. It tests knowledge of last-observation-carried-forward, index preservation, and avoiding mutation of the input.
Implement `forward_fill(s)`, which takes a pandas `Series` that may contain `NaN` gaps and returns a new `Series` where each missing value is replaced by the most recent preceding non-missing value.
Requirements:
- Fill each `NaN` with the last preceding non-missing value.
- Leave leading `NaN`s (those with no prior value) unchanged.
- Return a new `Series` with the original index and order preserved. Do not mutate the input.
For example:
```python
forward_fill(pd.Series([1.0, np.nan, np.nan, 4.0, np.nan]))
# -> pd.Series([1.0, 1.0, 1.0, 4.0, 4.0])
forward_fill(pd.Series([np.nan, 2.0, np.nan]))
# -> pd.Series([np.nan, 2.0, 2.0])
```
```hint Look for the built-in
This is the "last observation carried forward" pattern, and pandas has a method for it. Check what that method does with `NaN`s at the very start and whether it returns a new object or changes the input.
```
### What a Strong Answer Covers
- The pandas call that carries the last valid value forward, and why it matches the requirement.
- What happens to leading `NaN`s.
- Why the result is a new Series with the original index and order, and the input is left alone.
- Time and space complexity, and the fact that the fill follows the current row order.
### Follow-up Questions
- How would you forward fill without `ffill`, using NumPy?
- How would you forward fill within groups, such as per user, so a value never carries over from one group to the next?
- How would you limit how far a value is carried, for example across at most two consecutive gaps?
- What has to be true about the row order before you forward fill time-series data?
Overview: Write a pandas function that forward fills missing values in a Series with the most recent preceding valid value while leaving leading gaps alone. It tests knowledge of last-observation-carried-forward, index preservation, and avoiding mutation of the input.
Implement forward_fill(s), which takes a pandas Series that may contain NaN gaps and returns a new Series where each missing value is replaced by the most recent preceding non-missing value.
Requirements:
Fill each
NaN
with the last preceding non-missing value.
Leave leading
NaN
s (those with no prior value) unchanged.
Return a new
Series
with the original index and order preserved. Do not mutate the input.