Forward-fill gaps
A column contains gaps that should inherit the most recent available value.
Polars · Module
Expr.fill_null replaces null values with a literal, expression, or supported strategy such as forward, backward, min, max, mean, zero, or one. A limit can bound consecutive replacements for forward and backward filling.
This expression replaces null entries either with a supplied literal or expression, or by applying a supported strategy such as forward, backward, minimum, maximum, mean, zero, or one. The optional limit restricts how many consecutive nulls forward or backward filling may replace.
Expr.fill_null(value: Any | Expr | None = None, strategy: FillNullStrategy | None = None, limit: int | None = None) → Expr| Name | Type | Description |
|---|---|---|
value | Any | Expr | None = None | Value used to fill null values. |
strategy | FillNullStrategy | None = None | Strategy used to fill null values. Supported values are None, forward, backward, min, max, mean, zero, and one. |
limit | int | None = None | Number of consecutive null values to fill when using the forward or backward strategy. |
Expr
import polars as pl
df = pl.DataFrame({"value": [1, None, 3, None]})
result = df.with_columns(
pl.col("value").fill_null(strategy="forward", limit=1)
)
print(result)Replaces each fillable null with the preceding non-null value, limited to one consecutive null.
A column contains gaps that should inherit the most recent available value.
Missing values should use a column-derived calculation rather than a fixed constant.
Only a bounded run of consecutive missing values should be propagated.
It returns an Expr that fills null values with either value or a supported strategy. The strategy can be forward, backward, min, max, mean, zero, or one.
Follow-up: How would you prevent an unbounded forward fill? Pass a limit, which controls the number of consecutive nulls filled by forward or backward strategies.
The limit is the number of consecutive null values filled when using forward or backward filling. It does not define a general row limit for every strategy.
Follow-up: Which argument would you use to replace nulls with a computed column-dependent result? Supply an expression through value.
value accepts a literal or expression used as the replacement. If a neighboring-value or aggregate-style policy is preferable, strategy selects the filling behavior instead.
Follow-up: What should be used for missing floating-point NaN values? Use fill_nan rather than fill_null.
Expr.interpolateExpr.fill_nanDataFrame.fill_nullSeries.fill_null