Sub topic 7
Filling gaps with ffill, bfill, and interpolate
This chapter assumes you can build a DatetimeIndex, write a frequency string such as "D" or "W", and call resample() to downsample. It covers what happens when you go the other way, to a finer frequency, and the new rows have no data.
Why upsampling creates gaps
Upsampling asks for bins that are shorter than the spacing of your observations. A weekly series resampled to "D" gets six new daily rows between each pair of weekly values. pandas has no data for those rows, so it has to decide what to put there.
Calling resample("D") alone does nothing visible, because it returns a Resampler object. You must call a method on it. The three you will use most are:
ffill(): carry the last known value forward.bfill(): pull the next known value backward.interpolate(): compute values on a line (or curve) between known points.
If you call asfreq() instead, the new rows stay NaN. That is the "no fill" option, and the last chapter section compares it with these three.
Forward fill, backward fill, and linear interpolation
The series below holds one value per Monday. The first Monday of 2024 is January 1.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=3, freq="W-MON")
s = pd.Series([10.0, 20.0, 30.0], index=idx)
r = s.resample("D")
out = pd.DataFrame({
"ffill": r.ffill(),
"bfill": r.bfill(),
"linear": r.interpolate(),
})
print(out.head(9))The output is:
ffill bfill linear
2024-01-01 10.0 10.0 10.000000
2024-01-02 10.0 20.0 11.428571
2024-01-03 10.0 20.0 12.857143
2024-01-04 10.0 20.0 14.285714
2024-01-05 10.0 20.0 15.714286
2024-01-06 10.0 20.0 17.142857
2024-01-07 10.0 20.0 18.571429
2024-01-08 20.0 20.0 20.000000
2024-01-09 20.0 30.0 21.428571Each method answers a different question about the days between two readings:
ffillassumes the value stays the same until a new reading arrives. This suits a state, such as a price list, a configured limit, or an account balance.bfillassumes the value was already true before it was reported. It suits cases like a monthly figure that applies to the days leading up to its report date.interpolateassumes the value moves steadily. The step here is (20 − 10) / 7 ≈ 1.4286 per day. It suits a smoothly varying measurement such as temperature or a sensor level.
Existing observations are never changed. On January 1 and January 8, all three columns agree with the original data.
Limiting how far a fill reaches
A fill can silently turn a long outage into confident-looking data. Both ffill() and bfill() accept limit, the maximum number of consecutive new rows to fill.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=3, freq="W-MON")
s = pd.Series([10.0, 20.0, 30.0], index=idx)
limited = s.resample("D").ffill(limit=2)
print(limited.head(5))January 2 and 3 receive 10.0. January 4 and later, up to January 7, stay NaN, because the fill stops after two rows. Use limit when a value is trustworthy for a short time only. A price quote might be good for two days but not for two weeks.
interpolate() also takes limit. Pandas fills the first limit rows after each known value and leaves the rest of the gap as NaN.
Choosing the interpolation method
The default interpolate() method is "linear". Linear interpolation ignores the index and treats the rows as evenly spaced. After a clean upsample the rows are evenly spaced, so this is correct. If you interpolate a series whose timestamps are irregular, pass method="time", which weights by the actual time distance:
irregular = pd.Series(
[1.0, None, None, 4.0],
index=pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-03", "2024-01-10"]),
)
print(irregular.interpolate(method="time"))The value on January 2 is 1.0 + 3.0 × (1/9) ≈ 1.33, not 2.0, because January 2 is one day into a nine-day span. Other methods such as "polynomial" or "spline" need the order= argument and the SciPy package. They can overshoot between points, so check the output before relying on it.
Edges of the series
Two edge cases surprise people.
First, ffill cannot fill rows before the first observation, because nothing precedes them. Those rows stay NaN. The same applies to bfill after the last observation.
Second, interpolate() does extrapolate at the end. By default it fills trailing NaN values by repeating the last valid value. Leading NaN values stay empty.
import numpy as np
import pandas as pd
s = pd.Series(
[np.nan, 1.0, np.nan, np.nan, 4.0, np.nan],
index=pd.date_range("2024-01-01", periods=6, freq="D"),
)
print(s.interpolate().tolist())
print(s.interpolate(limit_area="inside").tolist())The first line prints [nan, 1.0, 2.0, 3.0, 4.0, 4.0]. The last value is a copy of 4.0, not an estimate. The second line prints [nan, 1.0, 2.0, 3.0, 4.0, nan]. Setting limit_area="inside" restricts filling to gaps surrounded by real values. Use it whenever you do not want invented values beyond your data.
What the Resampler methods really use
resample("D").ffill() and resample("D").interpolate() work on the grid of new timestamps. For interpolate(), the observations that land exactly on a grid timestamp are the anchor points. If your data has times of day, such as readings at 09:30, then resample("D").interpolate() has no anchor at midnight. A safer pattern is to aggregate first and then interpolate:
daily = s_with_times.resample("D").mean().interpolate()In this pattern mean() places each reading in its day bin, and interpolate() then fills only the days that had no readings at all. The cost is that each day's value is now a daily average, not an exact reading. Here s_with_times stands for any series with timestamps that include a time of day.
Comparing the options
| Method | New rows get | Uses future data | Typical use |
|---|---|---|---|
| `asfreq()` | `NaN` | No | Put data on a regular grid and keep gaps visible |
| `ffill()` | Last earlier value | No | Prices, settings, status |
| `bfill()` | Next later value | Yes | Values reported after the fact |
| `interpolate()` | Computed from both neighbors | Yes | Smooth measurements |
| `nearest()` | Closest known value in time | Yes | Match readings to the closest timestamp |
resample("D").ffill() and s.asfreq("D", method="ffill") give the same result in simple cases. Use resample when you might also downsample or aggregate in the same pipeline, and asfreq when you only need to reindex.
Common errors
- Forgetting to call a method.
s.resample("D")prints an object, not data. - Interpolating non-numeric columns.
interpolate()on object-dtype columns is deprecated and will fail in newer pandas. Select numeric columns first. - Filling before you decide how to treat true missing readings. After upsampling, a real
NaNin your data looks identical to a new empty row. Fill them with the same rule, or mark the originals first with a separate column such ass.isna(). - Using
interpolate()on a series where you actually need a carried value. A step function like a tax rate will produce meaningless in-between rates.
Exercise
A series of weekly stock counts (every Monday, 2024-01-01 to 2024-01-15) is upsampled with s.resample("D"). Which call fills each day with the most recent Monday's count, and fills at most 3 days after each Monday, and why would bfill() be a poor choice if you are building a model to predict next week's stock?
Show answer
Use s.resample("D").ffill(limit=3). Each Monday's count is repeated for the next three days, and days four to six stay NaN. bfill() copies the next Monday's count backward onto earlier days, so a model would see a future value as if it were already known. That is data leakage and makes the model look better in testing than it will perform in production.