skip to content

A pandas Series of minute-level sensor temperatures has three-minute dropouts and one three-hour outage; what does ffill(limit=5) do to each?

level: middleimportance: must knowfreq 60%

answer

  1. last valid observation carried forward
  2. limit counts consecutive rows per gap
  3. a long gap is only partly filled
  4. limit_area: inside or outside
  5. fillna(method=) no longer exists

basics

~20 s

ffill copies the last valid reading forward, so each three-minute dropout is filled completely. limit=5 caps each gap at five filled rows, so the outage gets five copies at its start and its remaining rows stay NaN.

solid answer

~40 s

`ffill()` propagates the last valid observation forward and `bfill()` propagates the next one backward. `limit` is the maximum number of consecutive missing values filled in each gap: a gap of three rows is filled entirely, while a gap of 180 rows gets its first five filled and keeps 175 `NaN`. So `limit` does not skip long gaps, it truncates them, and a chart would show a flat five-minute stub before the hole. `limit_area='inside'` fills only gaps with valid values on both sides and `'outside'` only leading or trailing ones. `limit` counts rows, not time, so on an irregular index five rows are not five minutes. In pandas 3.0 `fillna(method='ffill')` is removed and raises `TypeError`; call `ffill()` directly.

code

python · 18 lines
python
import numpy as np
import pandas as pd

idx = pd.date_range("2026-03-01 00:00", periods=240, freq="min")
temp = pd.Series(np.linspace(18.0, 24.0, 240), index=idx)
temp.iloc[10:13] = np.nan     # three-minute dropout
temp.iloc[40:220] = np.nan    # three-hour outage

filled = temp.ffill(limit=5)
print(filled.iloc[10:13].isna().sum())   # short dropout fully filled
print(filled.iloc[40:45].isna().sum())   # first 5 minutes of the outage filled
print(filled.iloc[45:220].isna().sum())  # the remaining 175 stay missing


try:
    temp.fillna(method="ffill")      # removed in pandas 3.0
except TypeError as err:
    print(type(err).__name__, err)

go deeper

for a junior

Recall that ffill copies the previous valid value forward, bfill copies the next one backward, and that both are separate methods rather than fillna options.

for a middle

Explain that limit fills at most that many consecutive gaps per run, so long runs are cut short rather than skipped, and what limit_area inside and outside change.

for a senior

Show how a truncated long gap fabricates plausible readings, and how to mask runs over a threshold; flag fillna(method=) calls as pandas 3.0 upgrade breakers.

for a principal

Decide where a maximum carry-forward window is set for the team's sensor data and make it explicit in code, so nobody relies on limit to skip long outages.

## What ffill and bfill do **`ffill()`** (forward fill) replaces each missing value with the **last valid observation before it**. **`bfill()`** (backward fill) replaces it with the **next valid observation after it**. On a DataFrame both work column by column by default (`axis=0`); `axis=1` fills across the columns of each row instead. Both return a new object of the same shape and dtype family, and both leave a gap alone when there is nothing to copy from: - `ffill()` cannot fill **leading** gaps, because no earlier value exists. - `bfill()` cannot fill **trailing** gaps, because no later value exists. - Chaining `s.ffill().bfill()` fills both ends, at the cost of copying the first reading backwards in time. A short illustration on `[NaN, 20.0, NaN, NaN, 24.0, NaN]`: - `ffill()` gives `[NaN, 20.0, 20.0, 20.0, 24.0, 24.0]`: the leading gap stays. - `bfill()` gives `[20.0, 20.0, 24.0, 24.0, 24.0, NaN]`: the trailing gap stays. - `ffill(limit=1)` gives `[NaN, 20.0, 20.0, NaN, 24.0, 24.0]`: only the first row of the two-row gap is filled. ## How limit behaves on short and long gaps The signature is `ffill(*, axis=None, inplace=False, limit=None, limit_area=None)`, and `bfill` mirrors it. The docstring defines `limit` as the maximum number of **consecutive** missing values to fill, and says that a gap with more than this number of consecutive missing values is **only partially filled**. Applied to minute-level IoT readings: | Gap | Length | Result of `ffill(limit=5)` | |---|---|---| | sensor dropout | 3 rows | all 3 filled with the reading before it | | sensor dropout | 5 rows | all 5 filled | | outage | 180 rows | first 5 filled, 175 still `NaN` | Two consequences matter in practice: 1. **`limit` truncates; it does not skip.** People expect "only fill gaps up to five minutes long". pandas instead fills the first five rows of every gap, so the outage now starts with five copied readings that look like real data. 2. **`limit` counts rows, not time.** On a regular one-minute index five rows are five minutes. On an irregular index, five rows can span seconds or hours. Leaving a long gap entirely empty takes one more step: label each run of gaps, measure its length, and mask the filled values in runs longer than the threshold. ## limit_area: inside or outside the valid values `limit_area` was added in pandas 2.2 and restricts where filling happens: - `None` (default): no restriction. - `'inside'`: only gaps that have valid values on **both sides**, so leading and trailing gaps stay missing. - `'outside'`: only gaps **before the first** or **after the last** valid value. `limit_area='inside'` is useful when a sensor started late or stopped early and you do not want its first or last reading smeared across time it never measured. It does not help with the long-outage problem, because that outage is itself an inside gap. ## The pandas 3.0 removal Before pandas 2.1 the usual spelling was `df.fillna(method='ffill')` or `method='pad'`. pandas 2.1 deprecated the `method` keyword of `fillna`, and pandas 3.0 removed it: - `df.fillna(method='ffill')` now raises `TypeError` for an unexpected keyword argument. - `df.interpolate(method='ffill')` (or `'pad'`, `'bfill'`, `'backfill'`) was deprecated in 2.1 and in pandas 3.0 raises `ValueError`. - The replacements are `df.ffill()` and `df.bfill()`, with the same `limit` meaning. Code written for pandas 1.x often fails on these calls first during an upgrade, so recognising them is part of reading older notebooks. ## Dtype and copying Forward fill copies existing values, so the column dtype does not need to widen: a `float64` column stays `float64`, and a `datetime64` column stays a datetime column. Like `fillna`, the methods return a new object; with `inplace=True` pandas 3.0 returns the modified object rather than `None`, but assigning the result is the clearer form. ## What this leaf does not cover Forward-filling **within each device** (so readings from one sensor never leak into the next) is a group-transform operation and is covered with group transforms. Filling the empty bins created by upsampling a series to a finer frequency belongs with resampling. Whether forward fill is an honest model for a temperature gap at all is a data decision, discussed in the library-neutral material on missing values.

  • How would you forward-fill only gaps of at most five rows and leave longer gaps completely empty?
    Label each run of gaps with `run_id = s.notna().cumsum()`, compute each run's length by counting missing values per `run_id`, and build a mask of rows in runs longer than five. Then take `s.ffill()` and set the masked rows back to `NaN`, for example with `filled.mask(long_gap)`. `limit` alone cannot do this because it fills the first rows of every gap.
  • What does s.ffill(limit_area='inside') leave missing?
    Every gap that is not enclosed by valid values: the leading gap before the first reading and the trailing gap after the last one. Gaps between two valid readings are filled, subject to `limit` if it is also given.
  • On a DataFrame, does ffill() copy values between columns?
    Not by default. With `axis=0` each column is filled from its own earlier rows, independently. Passing `axis=1` fills each row from the column to its left, which only makes sense when the columns are an ordered sequence of the same quantity.

  • Believing limit=5 skips gaps longer than five rows entirely.
  • Assuming limit on ffill counts minutes rather than rows.
  • Expecting ffill() to fill gaps before the first valid value.
  • Writing fillna(method='ffill'), which raises TypeError in pandas 3.0.
  • Thinking ffill() on a frame copies values across columns by default.

Assumes pandas 3.0, where fillna(method='ffill') is removed (deprecated in 2.1) and raises TypeError; ffill() and bfill() replace it, with limit_area available since 2.2.