Sub topic 8
Interpolating ordered data
This chapter assumes you can build a Series and DataFrame, know that np.nan marks a missing float, and have used fillna with a constant. Interpolation estimates a missing value from the values around it. It suits data with a meaningful order, such as a time series or a sensor reading.
Fill versus interpolate
Forward fill copies the last known value. Backward fill copies the next known value. interpolate instead draws a line between the known neighbours and places the missing points on it.
import numpy as np
import pandas as pd
s = pd.Series([1.0, np.nan, np.nan, 4.0, np.nan])
print(s.ffill())
print(s.bfill())
print(s.interpolate())The output shows the difference:
| Position | Original | ffill | bfill | interpolate |
|---|---|---|---|---|
| 0 | 1.0 | 1.0 | 1.0 | 1.0 |
| 1 | NaN | 1.0 | 4.0 | 2.0 |
| 2 | NaN | 1.0 | 4.0 | 3.0 |
| 3 | 4.0 | 4.0 | 4.0 | 4.0 |
| 4 | NaN | 4.0 | NaN | 4.0 |
The two gaps between 1.0 and 4.0 become 2.0 and 3.0, evenly spaced. The last value has no known value after it, so bfill leaves it missing. By default interpolate copies the last known value forward into a trailing gap, so it gives 4.0 there.
Choosing a method
The method argument controls how values are estimated. The default is "linear", which ignores the index and treats the points as equally spaced. Other common choices:
"time"uses aDatetimeIndexand weights each point by its real time gap."index"or"values"uses the numeric index values as the x-axis."nearest"copies the closest known value."polynomial"and"spline"fit curves. They need anorderargument and the SciPy package.
Use "time" when your timestamps are uneven. Plain linear interpolation would place a point as if the readings were equally spaced.
import numpy as np
import pandas as pd
idx = pd.to_datetime(["2026-01-01", "2026-01-02", "2026-01-05"])
s = pd.Series([10.0, np.nan, 40.0], index=idx)
print(s.interpolate())
print(s.interpolate(method="time"))Linear interpolation returns 25.0 for January 2, the midpoint of the three rows. Time-based interpolation returns 17.5, because January 2 is only one day into a four-day span (10 + 30 × 1/4).
Limiting how far it reaches
A long gap often should not be filled at all. Two arguments restrict the result:
limitis the maximum number of consecutive missing values to fill.limit_area="inside"fills only gaps that have known values on both sides. It leaves leading and trailing gaps alone.
import numpy as np
import pandas as pd
s = pd.Series([np.nan, 1.0, np.nan, np.nan, np.nan, 5.0, np.nan])
print(s.interpolate(limit=2, limit_area="inside"))The leading and trailing values stay missing. The three-value gap in the middle is filled for only its first two points, so the third stays missing. The filled points follow the line computed for the whole gap (2.0 and 3.0, not a line recomputed for a shorter gap).
Gotchas
- Order matters. Interpolation uses row position or the index, so sort first. On unsorted data the result is meaningless.
- Interpolating across groups. On stacked data, such as one block of rows per sensor, a plain call can blend the end of one group into the start of the next. Apply it per group, for example
df.groupby("sensor")["value"].transform(lambda s: s.interpolate()). - Invented values. Interpolated numbers look like real measurements. Do not use them for data that jumps, such as categories or counts of events. Keep a record of which values were estimated, for example with
s.isna()saved before filling. - Non-numeric columns. Interpolating an object column is deprecated. Convert the column to a numeric type first.
Exercise
A Series has a DatetimeIndex with readings on days 1, 2 and 9. The value on day 2 is missing, and the values on days 1 and 9 are 8.0 and 16.0. Will interpolate() or interpolate(method="time") give a value closer to 8.0, and why?
Show answer
interpolate(method="time") gives the closer value. Day 2 is 1 day into an 8-day span, so the result is 8 + 8 × 1/8 = 9.0. Plain interpolate() ignores the dates and places day 2 at the midpoint of the three rows, giving 12.0.