Sub topic 7
Forward and backward fill
This chapter assumes you can already use isna and fillna with constants and statistics, as covered earlier in this tutorial. It also assumes you can build a Series or DataFrame with a sorted or datetime index.
Constants and statistics ignore position. Many datasets do not: a sensor reading, a price, or a customer's plan tier usually stays the same until something changes it. For that kind of data, copying a neighbouring value into the gap is often more honest than inserting an average. Forward fill and backward fill do exactly that.
What the two methods do
ffill()is forward fill. Each missing value takes the last non-missing value that appears before it.bfill()is backward fill. Each missing value takes the next non-missing value that appears after it.
Both work on position, not on labels. "Before" and "after" mean row order as it currently sits in the object. The two methods exist on both Series and DataFrame.
import numpy as np
import pandas as pd
idx = pd.date_range("2026-01-01 00:00", periods=6, freq="h")
temp = pd.Series([np.nan, 20.1, np.nan, np.nan, 21.0, np.nan], index=idx)
print(temp.ffill())
print(temp.bfill())The forward-filled values are NaN, 20.1, 20.1, 20.1, 21.0, 21.0. The backward-filled values are 20.1, 20.1, 21.0, 21.0, 21.0, NaN.
Both results still contain one NaN. Forward fill has nothing to copy for the leading gap, because no valid value precedes it. Backward fill has nothing to copy for the trailing gap. This is the first edge case to remember: a fill can only propagate from a value that exists in the direction it travels.
Combining the two
To close both ends of a series, chain the methods. Run the one you trust more first, because it takes priority wherever both could fill a cell.
import numpy as np
import pandas as pd
idx = pd.date_range("2026-01-01 00:00", periods=6, freq="h")
temp = pd.Series([np.nan, 20.1, np.nan, np.nan, 21.0, np.nan], index=idx)
print(temp.ffill().bfill())The result is 20.1, 20.1, 20.1, 20.1, 21.0, 21.0. The leading gap now uses the first valid value, which is a weaker assumption than the gaps in the middle. Decide on purpose whether that is acceptable. Backward-filling a leading gap claims the world was already in its first observed state before you saw it.
| Call | Direction | Leading gap | Trailing gap |
|---|---|---|---|
| `s.ffill()` | previous value forward | stays missing | filled |
| `s.bfill()` | next value backward | filled | stays missing |
| `s.ffill().bfill()` | forward, then backward | filled | filled |
Limiting how far a value travels
An unlimited forward fill can carry a stale value across a very long outage. The limit parameter caps the number of consecutive missing values filled in each gap.
import numpy as np
import pandas as pd
idx = pd.date_range("2026-01-01 00:00", periods=6, freq="h")
temp = pd.Series([np.nan, 20.1, np.nan, np.nan, 21.0, np.nan], index=idx)
print(temp.ffill(limit=1))The output is NaN, 20.1, 20.1, NaN, 21.0, 21.0. The two-row gap in the middle receives one filled value, and the second row stays missing. The limit applies per gap, not to the whole series, so each run of missing values gets its own allowance.
A related option is limit_area. With limit_area="inside", only gaps that have valid values on both sides are filled. With limit_area="outside", only the edges are filled.
import numpy as np
import pandas as pd
idx = pd.date_range("2026-01-01 00:00", periods=6, freq="h")
temp = pd.Series([np.nan, 20.1, np.nan, np.nan, 21.0, np.nan], index=idx)
print(temp.ffill(limit_area="inside"))This gives NaN, 20.1, 20.1, 20.1, 21.0, NaN. Interior gaps are bridged while the leading and trailing gaps are left alone, which is useful when you want to avoid making claims beyond the observed range.
Filling across columns
By default the fill runs down each column. Pass axis=1 on a DataFrame to run it across each row, from left to right for ffill and right to left for bfill.
import numpy as np
import pandas as pd
wide = pd.DataFrame({
"q1": [5.0, np.nan],
"q2": [np.nan, 7.0],
"q3": [np.nan, np.nan],
})
print(wide.ffill(axis=1))Row 0 becomes 5, 5, 5. Row 1 becomes NaN, 7, 7, because q1 has nothing to its left. Only use this when the column order is meaningful, such as quarters or time steps. Filling across unrelated columns like age and income would copy values between fields that have nothing to do with each other.
Order matters: sort first
Because the methods follow row position, unsorted data produces wrong answers without any error. If your rows arrive in an arbitrary order, "the previous row" is arbitrary too.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"when": pd.to_datetime(["2026-03-03", "2026-03-01", "2026-03-02"]),
"price": [np.nan, 100.0, np.nan],
})
df = df.sort_values("when").reset_index(drop=True)
df["price"] = df["price"].ffill()
print(df)After sorting, March 1 comes first, so both later days receive 100.0. Without the sort, the March 3 row would sit first with nothing to copy from, and it would stay missing.
Filling within groups
A plain ffill() on a stacked table ignores boundaries between entities. The last reading from sensor a can leak into the first gap of sensor b. Use groupby so the fill restarts for every group.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"sensor": ["a", "b", "a", "b", "a", "b"],
"reading": [1.0, 10.0, np.nan, np.nan, 3.0, np.nan],
})
df["global"] = df["reading"].ffill()
df["by_sensor"] = df.groupby("sensor")["reading"].ffill()
print(df)The global column is 1, 10, 10, 10, 3, 3. It puts a value from sensor b into sensor a's row 2, and a value from a into b's row 5. The by_sensor column is 1, 10, 1, 10, 3, 10, which is correct for each sensor. The grouped ffill returns a result aligned to the original index, so you can assign it straight back, with no transform needed.
Within groupby, the limit argument also applies per group and per gap. As with any fill that depends on order, sort by time inside each group before you fill.
Choosing between forward and backward
The two methods answer different questions.
- Forward fill says "the state persisted until the next observation". This fits records that are logged only on change, such as a price list, a subscription tier, or a configuration setting.
- Backward fill says "the state was already true before we observed it". This fits cases such as a label recorded at the end of a period that applies to the whole period.
Backward fill also carries a modelling risk. It uses information from the future to fill the past. If you are building features for a forecast or any model that predicts a later event, a backward-filled value can leak the answer into the training data. For that work, forward fill, or a fill limited to past values, is the safer default.
Things to watch for
- Do not use the old
methodargument.fillna(method="ffill")is deprecated in current pandas. Callffill()orbfill()directly. They are shorter and make the direction obvious. - Present values are never changed. A fill touches only missing cells. If a bad value is already there, forward fill will happily copy it onto the next gaps.
- Placeholders must already be missing. A
-999code is notNaN, so no fill touches it. Convert placeholders first, as shown in the chapter on loading sentinels. - A fill can hide the amount of missing data. After filling,
isna().sum()reports zero. Record the original counts, or keep a flag column such asdf["price_was_missing"] = df["price"].isna()before filling. - Long gaps deserve scrutiny. Without
limit, a value from months ago can fill a recent row. Set a limit that matches how long the real-world state could plausibly persist. - Neither method estimates change. If a value is rising from 1 to 4 over three steps, copying 1 forward produces a staircase. The next chapter covers interpolation, which draws a line between the known points instead.
Exercise
A DataFrame df is sorted by day and has columns store, day and stock. Each store logs stock only when it changes, so unchanged days are NaN. The first row of each store may also be NaN. Write the line that fills the gaps correctly, allows a value to be carried for at most 3 consecutive days, and does not copy anything from one store to another. What happens to a store's leading NaN?
Show answer
df["stock"] = df.groupby("store")["stock"].ffill(limit=3). Grouping by store restarts the fill for each store, so no value crosses a store boundary. A forward fill has no earlier value to copy, so a store's leading NaN stays missing. Separately, any gap longer than 3 days is filled for only its first 3 days.