Sub topic 7
Working with null values
This chapter assumes you know how to build a DataFrame and write expressions inside select, with_columns and filter. Here you will learn how Polars represents missing data and how null behaves in calculations.
Null is the missing-value marker
Polars uses null for a missing value in every data type. None in Python input becomes null. Floating-point columns also have NaN ("not a number"), which is a real float value and is not the same as null.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"score": [90, None, 70, None],
"bonus": [5, None, None, 2],
}
)
print(df.null_count())
print(df.select(pl.col("score").is_null().alias("score_missing")))null_count() returns one row with the number of nulls in each column. is_null() and is_not_null() return a boolean for each row.
How null propagates
Arithmetic on a null gives null. Aggregations skip nulls.
print(
df.with_columns((pl.col("score") + pl.col("bonus")).alias("total"))
)
print(df.select(pl.col("score").mean(), pl.col("score").count()))Only Ana has both values, so only her total is non-null. The mean is 80.0, computed from the two non-null scores. count() returns 2 because it counts non-null values. Use pl.len() to count all rows.
Comparisons also return null when one side is null. This affects filter.
print(df.filter(pl.col("score") > 80))
print(df.filter((pl.col("score") > 80) | pl.col("score").is_null()))filter keeps only rows where the predicate is true. A null predicate is not true, so those rows are dropped. The second query keeps the null rows on purpose.
Replacing and removing nulls
Choose a strategy that fits the meaning of the data.
print(
df.with_columns(
pl.col("score").fill_null(0).alias("zero_filled"),
pl.col("score").fill_null(pl.col("score").mean()).alias("mean_filled"),
pl.col("score").fill_null(strategy="forward").alias("carried"),
pl.coalesce(pl.col("score"), pl.col("bonus"), pl.lit(0)).alias("first_found"),
)
)
print(df.drop_nulls(subset="score"))fill_nullaccepts a literal, an expression, or astrategysuch as"forward","backward","min"or"mean".pl.coalescereturns the first non-null value across the expressions you give it, row by row.drop_nullsremoves rows with a null. Thesubsetargument limits the check to specific columns. Without it, a null in any column removes the row.
NaN is separate
fill_null does not touch NaN, and fill_nan does not touch null.
s = pl.Series("x", [1.0, float("nan"), None])
print(s.is_nan())
print(s.fill_nan(None))is_nan() returns null for the null entry. Passing None to fill_nan turns NaN into null, so one null-handling step then covers both.
Exercise
A DataFrame has a score column with values [60, None, 80]. What does df.filter(pl.col("score") != 60) return, and how would you keep the null row too?
Show answer
It returns only the row with 80. The null row is dropped because null != 60 evaluates to null, which filter treats as not true. To keep it, use df.filter((pl.col("score") != 60) | pl.col("score").is_null()).