Skip to content

Fill nulls: fillNulls

Replace missing values using a strategy.

Use cases

  • Backfill a constant like "Unknown" for a missing category.
  • Impute a numeric column with its mean/median so rows aren't lost.
  • Carry the last known value forward (ffill) in a time series.

What it does

Replaces nulls in the target columns without removing rows. Unlike Drop nulls, every row survives.

Fill nulls (strategy=constant, value=Unknown, columns=[region])
Before
order_idregionamount
1001North120.5
1002null89
1003Southnull
1004null42.25
4 rows · 3 cols
After
order_idregionamount
1001North120.5
1002Unknown89
1003Southnull
1004Unknown42.25
4 rows · 3 cols

Configuration

Config keyTypeRequiredDescription
strategystringNoconstant (default), mean, median, mode, min, max, zero, ffill, bfill
valueanyConditionalRequired when strategy is constant
columnsstring[]NoLimit to these columns (otherwise all)

The mean, median, min, and max strategies are computed per column from the non-null values; mode uses the most frequent value; ffill/bfill propagate the previous/next value.

Generated Python code

This example fills missing region values with Unknown (strategy: constant, columns: ["region"]). Other columns and every row are retained.

pandas

python
df_2 = df_1.copy()
for _col in ['region']:
    try:
        _fill = pd.array(['Unknown'], dtype=df_2[_col].dtype)[0]
    except (ValueError, TypeError):
        continue  # the value does not fit this column's type
    df_2[_col] = df_2[_col].fillna(_fill)

Polars

python
_sch = df_1.collect_schema()
_fills = []
for _col in ['region']:
    try:
        _fills.append(pl.col(_col).fill_null(pl.Series(['Unknown']).cast(_sch[_col])[0]))
    except pl.exceptions.PolarsError:
        continue  # the value does not fit this column's type
df_2 = df_1.with_columns(_fills)

Tips & common mistakes

  • A value is only needed for constant. Computed strategies (mean, median, …) ignore it.
  • A constant only fills columns whose type it fits. Unknown leaves numeric columns alone, listed or not; 0 fills numeric and text columns.
  • mean/median need numeric columns. Restrict columns so the strategy only touches columns it applies to.

See also