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
fill_nullreplaces gaps with a constant or expression.drop_nullskeeps only complete rows.null_countreports gaps per column.
Keywords and builtins used here
as
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.
Step 3 of 3 in Filtering & sorting, step 11 of 32 in Polars.