Forward-fill missing values within each group of a pandas DataFrame
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `group_forward_fill(df, group_col, value_col)`, which forward-fills missing values in `value_col` independently within each group defined by `group_col`. Return a new DataFrame.
The function must:
- Never carry a value across a group boundary (groups may be interleaved).
- Leave leading NaNs within a group (before any observed value) as NaN.
- Preserve the original row order, index, shape and column order. Do not sort.
- Modify only `value_col`, and never mutate the input `df`.
Example:
```python
df = pd.DataFrame({
"g": ["a", "a", "b", "b", "a"],
"v": [None, 1.0, None, 5.0, None],
})
group_forward_fill(df, "g", "v")
# g v
# a NaN # leading NaN in group 'a' stays NaN
# a 1.0
# b NaN # leading NaN in group 'b' stays NaN
# b 5.0
# a 1.0 # filled from previous 'a' value, not from 'b'
```
```hint Let pandas restart the fill
Look for a pandas operation that already restarts at every group boundary and returns values aligned to the original index. Then you never have to split, sort or reassemble the frame yourself.
```
### Constraints & Assumptions
- The frame is already in the intended within-group order, so "previous value" means the previous row of the same group.
### What a Strong Answer Covers
- How the fill stays inside each group even when the groups are interleaved.
- Why leading NaNs in a group stay NaN.
- How the result keeps row order, index, shape and column order without sorting, and how the input stays unmodified.
- The time and space cost, plus edge cases such as an all-NaN group or a missing group key.
### Follow-up Questions
- How would you extend this to fill several value columns at once?
- Why prefer `groupby().ffill()` over `groupby().apply()`?
- How would you add a limit on consecutive fills, or a backward fill?
Overview: Write a pandas function that forward-fills missing values separately within each group of a DataFrame, where groups can be interleaved and the row order must not change. It tests group-aware transforms, index alignment on assignment, leading NaNs, and avoiding mutation of the input frame.