Linear Interpolation of Interior NaNs in a pandas Series
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `interpolate_linear(s)` that fills the interior missing values of a numeric pandas `Series` using linear interpolation, with the points treated as equally spaced, and returns a new `Series`.
The function must follow these rules:
- Only interior gaps are filled. A `NaN` with no valid value before it (a leading `NaN`) stays `NaN`, and so does a `NaN` with no valid value after it (a trailing `NaN`).
- The original index and order are preserved, and the input Series is not modified.
For example:
```python
import numpy as np
import pandas as pd
interpolate_linear(pd.Series([0.0, np.nan, np.nan, 3.0]))
# -> pd.Series([0.0, 1.0, 2.0, 3.0])
interpolate_linear(pd.Series([np.nan, 1.0, np.nan, 5.0, np.nan]))
# -> pd.Series([np.nan, 1.0, 3.0, 5.0, np.nan])
```
```hint Test the edges
Run your function on a Series that ends in NaN and check whether the last value is still missing.
```
### Constraints & Assumptions
- The input holds floats, with `NaN` marking a missing value.
- The index can be of any type (integers, strings, timestamps). Positions count as equally spaced whatever the index values are.
### What a Strong Answer Covers
- How the fill value for a gap is computed from its two neighbors when positions are equally spaced
- Correct handling of NaNs at both ends, including what the default pandas call does after the last valid value
- A new Series with the original index and order, leaving the input untouched
- Edge cases such as an all-NaN Series, a single valid value, and a non-numeric index
- Time and space complexity
### Follow-up Questions
- How does `method='time'` differ from the default, and when would you use it?
- How would you also fill the leading and trailing gaps, and what values would they get?
- How would you leave gaps longer than `k` consecutive values unfilled while still filling shorter ones?
- How would you get the same result without calling `Series.interpolate`?
Overview: Write a pandas function that fills interior NaN values in a numeric Series with linear interpolation while leaving leading and trailing gaps missing. It tests how well you know pandas interpolation defaults, edge handling, and how position-based filling differs from time-based filling.