Sub topic 8
Interpolating ordered data
This chapter covers Series.interpolate() and DataFrame.interpolate(). It assumes you know how to detect missing values with isna, how fillna, ffill and bfill work, and what a DatetimeIndex is. Examples use pandas 2.x.
What interpolation does
Forward fill and backward fill copy a neighbouring value into a gap. Interpolation estimates a value from the points on both sides of the gap. If a sensor reads 1.0, then nothing, then nothing, then 4.0, a linear estimate for the two missing readings is 2.0 and 3.0.
Interpolation is only meaningful when row order carries information, such as time or distance. For unordered records like a customer table, "the value between row 3 and row 5" means nothing. Use a constant, a statistic or a group-wise fill there.
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 last call returns 1.0, 2.0, 3.0, 4.0, 4.0. Two behaviours stand out:
- The two interior gaps are filled on a straight line between 1.0 and 4.0.
- The trailing gap has no right-hand neighbour, so pandas repeats the last valid value, 4.0. It does not extrapolate the trend.
The default method ignores your index
The default is method="linear". It treats the values as equally spaced, whatever the index says. The index labels are not used.
With an irregular index this gives a wrong answer without any error:
import numpy as np
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-05"])
s = pd.Series([10.0, np.nan, 40.0], index=idx)
print(s.interpolate()) # linear
print(s.interpolate(method="time")) # uses the datesLinear puts the midpoint, 25.0, on January 2. But January 2 is only one day into a four-day span, so the time-aware answer is 10 + 30 × 1/4 = 17.5. method="time" weights each gap by the actual time elapsed.
| Method | What it uses | Typical use |
|---|---|---|
| `"linear"` (default) | Row position only | Evenly spaced data |
| `"index"` or `"values"` | Numeric index values | Irregular numeric x-axis, such as distance |
| `"time"` | Datetime index values | Irregular timestamps |
| `"nearest"` | Closest valid point (needs SciPy) | Categorical-like or step data |
| `"polynomial"`, `"spline"`, `"pchip"`, `"cubic"` | Curve fit (needs SciPy) | Smooth physical signals |
"polynomial" and "spline" also need an order argument, for example s.interpolate(method="spline", order=3). Install SciPy before using any method in the last two rows.
import numpy as np
import pandas as pd
s = pd.Series([0.0, np.nan, 10.0], index=[0, 1, 10])
print(s.interpolate()) # position-based: 5.0 at label 1
print(s.interpolate(method="index")) # label-based: 1.0 at label 1Use "index" here. The label 1 sits one tenth of the way from 0 to 10, so the value should be 1.0.
Controlling how far a fill reaches
A fill that bridges one missing reading is reasonable. A fill that bridges three weeks of outage invents data. Three parameters limit the damage.
limit=nfills at mostnconsecutive missing values in each gap.limit_directionis"forward"(default),"backward"or"both". It sets which direction pandas fills from the known values.limit_areaisNone(default),"inside"or"outside"."inside"fills only gaps surrounded by valid values."outside"fills only gaps at the edges.
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().tolist())
print(s.interpolate(limit=2).tolist())
print(s.interpolate(limit_area="inside").tolist())
print(s.interpolate(limit_direction="both").tolist())The four results, in order:
[nan, 1, 2, 3, 4, 5, 5]. The leading NaN stays, and the trailing NaN repeats 5.[nan, 1, 2, 3, nan, 5, 5]. Only the first two NaNs of the three-point gap are filled. The unfilled value at position 4 is not recomputed to match, so the filled part still follows the full 1-to-5 line.[nan, 1, 2, 3, 4, 5, nan]. Only interior gaps are filled, and both edges stay missing.[1, 1, 2, 3, 4, 5, 5]. The leading NaN is filled backward with 1.
When you need no edge fill at all, limit_area="inside" is the safest choice. Edge values are extrapolation, and pandas performs that extrapolation by copying the nearest value.
Interpolating a DataFrame
On a DataFrame, interpolate() works down each column independently. With method="time" or "index", the shared index supplies the x-values for every column.
import numpy as np
import pandas as pd
idx = pd.date_range("2024-03-01", periods=5, freq="h")
df = pd.DataFrame(
{
"temp": [20.0, np.nan, 22.0, np.nan, 24.0],
"humidity": [50.0, 52.0, np.nan, np.nan, 60.0],
"station": ["A", "A", None, "A", "A"],
},
index=idx,
)
num = df.select_dtypes("number").interpolate(method="time")
df[num.columns] = num
print(df)The text column is excluded on purpose. Interpolating object columns is not supported, and recent pandas versions deprecate the old implicit behaviour. Select the numeric columns, interpolate them, and assign the result back. The missing station value is a label, so decide that separately, for example with ffill().
Gaps are measured per column. Here humidity has a two-point gap, so its two missing values become 54.0 and 56.0 when method="time" is used on the hourly index.
Choosing a method
Some guidance for common cases:
- Linear is a sound default. It never overshoots the neighbouring values, and it is easy to explain to others.
- Splines and polynomials can overshoot. A high-order polynomial through noisy points can swing well outside the range of the data between samples. Prefer
"pchip"when you want a smooth curve that stays within the neighbouring values. - Step-like data needs another approach. A thermostat setting or a price list holds its value until the next change. Interpolation would invent values that never existed, so
ffill()is the correct tool. - Counts and identifiers should not be interpolated. A result of 2.5 orders is not a valid count, and an interpolated ID is meaningless. Round the result only if the quantity is truly continuous underneath.
Common errors
- Using the default on irregular timestamps. Linear ignores the dates. Pass
method="time". - Interpolating unsorted data. The gap is filled from the neighbours in row order, not the neighbours in time.
- Forgetting SciPy. Methods such as
"spline"raise anImportErrorwhen SciPy is not installed. Linear,"time","index"and"pad"work without it. - Letting long gaps fill. Without
limitorlimit_area, a month-long outage between two readings becomes a clean straight line that looks like real data. - Using future values in a forecasting task. An interpolated value at time t depends on a reading after t. If you are building a model that predicts the future, that is leakage. Use
ffill()or a causal rule inside the training pipeline. - Expecting interpolation to repair the data in place.
interpolate()returns a new object. Assign it back, as indf["temp"] = df["temp"].interpolate(method="time").
Exercise
A Series has the DatetimeIndex 2024-06-01, 2024-06-02, 2024-06-10 and the values 8.0, NaN, 26.0. What value does interpolate() put on June 2, and what value does interpolate(method="time") put there? Which one is appropriate, and why?
Show answer
The default linear method gives 17.0, the midpoint of 8.0 and 26.0, because it ignores the dates and treats the three rows as evenly spaced. With method="time", June 2 is 1 day into a 9-day span, so the value is 8.0 + 18.0 × 1/9 = 10.0. The time-based result is appropriate because the rows are not evenly spaced in time.
Exercise
Given s = pd.Series([np.nan, 2.0, np.nan, np.nan, 8.0, np.nan]), write one call that fills only the gap between 2.0 and 8.0 and leaves both edge NaNs untouched. What does the result look like?
Show answer
s.interpolate(limit_area="inside"). The result is [NaN, 2.0, 4.0, 6.0, 8.0, NaN]. The interior gap is filled on a straight line, and neither edge value is filled, because limit_area="inside" restricts filling to gaps with valid values on both sides.