Fill short time-series gaps
A time-ordered table has short gaps, and later observations are the appropriate values to propagate backward.
Pandas · Module
DataFrame.bfill fills missing values by propagating the next valid observation backward along an axis. It can limit the number and position of values filled, or modify the DataFrame in place.
DataFrame.bfill replaces missing values by propagating the next non-missing observation backward along the selected axis. It returns a filled DataFrame unless inplace=True, in which case it modifies the object and returns None.
DataFrame.bfill(*, axis=None, inplace=False, limit=None, limit_area=None)| Name | Type | Description |
|---|---|---|
axis | {0 or 'index', 1 or 'columns'}, default None | Axis along which to fill missing values: 0 or 'index', or 1 or 'columns'. |
inplace | bool, default False | Whether to modify the DataFrame in place. |
limit | int, default None | Maximum number of consecutive missing values to fill; must be greater than zero when provided. |
limit_area | {None, 'inside', 'outside'}, default None | Restricts filling to all positions, missing values inside valid values, or missing values outside valid values; requires limit. |
DataFrame or None. The filled DataFrame is returned unless inplace=True, which returns None.
import pandas as pd
frame = pd.DataFrame({"a": [1, None, None, 4], "b": [None, 2, None, 3]})
filled = frame.bfill(limit=1)
print(filled)Creates a DataFrame and fills at most one consecutive missing value per gap using the next valid value.
A time-ordered table has short gaps, and later observations are the appropriate values to propagate backward.
Only interior missing runs should be completed while edge gaps remain missing.
A pipeline requires controlled mutation of an existing DataFrame object.
It performs backward filling: each missing value can receive the next valid observation later along the selected axis. By default, it operates on the index axis for a DataFrame.
Follow-up: How would you prevent leading or trailing gaps from being filled? Set limit_area='inside' while also specifying limit.
limit restricts how many consecutive missing entries are filled. A gap longer than the limit is only partially filled, and a non-None limit must be greater than zero.
Follow-up: How can you fill only missing values outside the valid-data region? Use limit_area='outside' with a specified limit.
The method returns a DataFrame containing the filled values when inplace=False. With inplace=True, it modifies the original object and returns None.
Follow-up: What alias-related concern follows from inplace=True? Other views, including no-copy column slices, may observe the mutation.
DataFrame.ffillDataFrame.fillnaSeries.bfillDataFrame.interpolate