typestar

Handling nulls in Python

Filling and dropping missing values in Polars.

import polars as pl

df = pl.DataFrame({
    "city": ["akl", "wlg", None, "chc"],
    "temp": [18, None, 12, 14],
})

filled = df.with_columns(
    pl.col("city").fill_null("unknown"),
    pl.col("temp").fill_null(pl.col("temp").mean()),
)

complete = df.drop_nulls()
missing = df.null_count()

How it works

  1. fill_null replaces gaps with a constant or expression.
  2. drop_nulls keeps only complete rows.
  3. null_count reports gaps per column.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
277
Tokens
109
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 62 seconds.

Type this snippet

Step 3 of 3 in Filtering & sorting, step 11 of 32 in Polars.

← Previous Next →