Statistical imputation
Replace missing numeric observations with a column statistic.
Polars · Module
Fills null values in a DataFrame with a supplied value or expression, or with a built-in strategy. It returns a DataFrame with the replacements applied.
Call this method on a DataFrame and provide either a replacement value, an expression, or a strategy. Strategies can derive replacements from neighboring values or column statistics; the optional limit restricts forward and backward filling, while matches_supertype controls compatible type matching.
DataFrame.fill_null(value: Any | Expr | None = None, strategy: FillNullStrategy | None = None, limit: int | None = None, *, matches_supertype: bool = True) → DataFrame| Name | Type | Description |
|---|---|---|
value | Any | Expr | None = None | Value used to fill null values. |
strategy | FillNullStrategy | None = None | Strategy used to fill null values; options are None, forward, backward, min, max, mean, zero, and one. |
limit | int | None = None | Number of consecutive null values to fill when using forward or backward. |
matches_supertype | bool = True | Fill all matching supertypes of the fill value. |
DataFrame with None values replaced by the filling strategy.
import polars as pl
df = pl.DataFrame({"a": [1, 2, None, 4], "b": [0.5, 4.0, None, 13.0]})
filled = df.fill_null(strategy="mean")
print(filled)Replaces nulls in each column with that column's mean.
Replace missing numeric observations with a column statistic.
Carry the previous or next available value through short gaps.
Apply a constant or computed replacement across compatible columns.
DataFrame.fill_null replaces None values and returns a DataFrame. It accepts a literal or expression through value, or a strategy such as forward, backward, min, max, mean, zero, or one.
Follow-up: How would you avoid filling every consecutive gap during propagation? Set limit, which bounds the number of consecutive nulls filled by forward or backward strategies.
The value parameter supplies the replacement, while strategy selects a built-in filling rule. The method returns a DataFrame whose None values have been replaced.
Follow-up: Can a replacement be computed rather than constant? Yes: pass an expression as value, allowing replacements computed from column data.
matches_supertype defaults to True and fills columns whose types match the supertype of the supplied fill value. This helps one replacement value apply across compatible column types.
Follow-up: How can type matching be made stricter? Set matches_supertype to False so compatible supertypes are not included.
DataFrame.fill_nanExpr.fill_nullSeries.fill_null