Sub topic 7
Forward and backward fill
This chapter assumes you can build a pandas Series and DataFrame, know that np.nan marks a missing float, and have used isna and fillna with a constant. It covers filling gaps by copying neighbouring values.
Why copy a neighbour
A constant or a mean ignores row order. Sometimes the order carries the meaning. A sensor reading that is missing for one minute is probably close to the reading before it. A price list that only records changes means "same as the last row". In these cases you can propagate a nearby value into the gap.
pandas gives you two methods:
ffill()is forward fill. It copies the last valid value forward, down the rows.bfill()is backward fill. It copies the next valid value backward, up the rows.
Comparing the methods
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 results differ at the edges, as the table shows.
| 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 |
ffill fills the last row because a valid value comes before it. bfill leaves it as NaN because no valid value comes after it. The same happens at the start of a series with ffill. Leading gaps stay missing under forward fill.
Limiting how far a value travels
A value copied across a long gap may no longer be believable. The limit argument caps how many consecutive gaps are filled.
import numpy as np
import pandas as pd
s = pd.Series([1.0, np.nan, np.nan, np.nan, 5.0])
print(s.ffill(limit=1))Only the first gap after the 1.0 is filled. The other two stay NaN, which is often what you want: a visible gap is more honest than a stale value.
Use sorted data
Forward fill uses row position, not the index label or any date column. If the rows are not in the right order, you copy the wrong neighbour. Sort first.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"day": pd.to_datetime(["2026-01-03", "2026-01-01", "2026-01-02"]),
"temp": [np.nan, 10.0, np.nan],
})
df = df.sort_values("day")
df["temp"] = df["temp"].ffill()
print(df)After sorting, January 2 and January 3 both receive 10.0. Without the sort, January 3 would come first and stay missing.
Filling several columns
On a DataFrame, ffill() works column by column. Each column uses its own previous valid value, so rows can end up mixing values from different original rows. Fill only the columns where this makes sense by selecting them.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"price": [9.5, np.nan, np.nan, 10.0],
"note": ["start", None, None, "end"],
})
df[["price"]] = df[["price"]].ffill()
print(df)Here price is filled but note keeps its gaps.
Exercise
Exercise
Given s = pd.Series([np.nan, 2.0, np.nan, np.nan, 7.0]), what does s.ffill().bfill() return, and why is chaining the two calls useful?
Show answer
It returns [2.0, 2.0, 2.0, 2.0, 7.0]. ffill fills positions 2 and 3 with 2.0 but leaves position 0 missing because no valid value comes before it. The following bfill fills position 0 with 2.0 from the next valid value. Chaining the two removes the leading gap that ffill alone cannot fill, but it also uses a future value for that first row.