For an offline consumption report (not a forecasting feature), an analyst fills gaps in a building's daily energy readings. The readings were logged on irregular dates, and some logged dates have no value. What does this snippet print?
import numpy as np
import pandas as pd
idx = pd.to_datetime(["2025-03-01", "2025-03-02", "2025-03-05",
"2025-03-06", "2025-03-10"])
s = pd.Series([10, np.nan, 50, np.nan, 90], index=idx)
print(s.interpolate().tolist())
print(s.interpolate(method="time").tolist())Show the answer and explanation
Correct answer: B, [10.0, 30.0, 50.0, 70.0, 90.0], then [10.0, 20.0, 50.0, 58.0, 90.0]: the default treats rows as equally spaced, while method="time" weights by elapsed days.
Explanation Missing Data
Series.interpolate() defaults to method="linear", which ignores the index and treats consecutive rows as equally spaced. Each gap is filled halfway between its neighbours: (10 + 50) / 2 = 30 and (50 + 90) / 2 = 70.
method="time" works on a DatetimeIndex and weights by elapsed time:
v = v₀ + (t − t₀) / (t₁ − t₀) × (v₁ − v₀)
| Gap | Neighbours | Share of the interval | time fill |
|---|---|---|---|
| 2 March | 1 March (10), 5 March (50) | 1 of 4 days | 10 + 0.25 × 40 = 20 |
| 6 March | 5 March (50), 10 March (90) | 1 of 5 days | 50 + 0.2 × 40 = 58 |
So the first line prints [10.0, 30.0, 50.0, 70.0, 90.0] and the second [10.0, 20.0, 50.0, 58.0, 90.0]. The values are floats because the series holds NaN.
Why the distractors fail: the default really does disregard the timestamps, which is why method="time" (and "index" for a numeric index) exists. It needs no regular frequency; uneven spacing is exactly its use case. And the larger weight belongs to the nearer reading: 2 March is one day from 1 March, so 10 gets weight 3/4 and 50 gets 1/4.
Both methods are two-sided and use the next reading. That is fine for offline cleaning like this report, but the same fill would leak future data if it fed a forecasting model.
Interview tip: for irregular sensor or transaction logs, say you would interpolate on time (or resample to a fixed grid first) and cap long gaps with limit, since a straight line across a two-week outage is a guess, not a measurement.