Sub topic 7
Working with null values
This chapter assumes you can build a DataFrame, write expressions with pl.col, and use select, with_columns and filter. It covers how Polars represents missing data, how nulls behave in common operations, and how to handle them deliberately.
What null means in Polars
A null is a missing value. Every data type can hold nulls: integers, strings, dates, lists. Polars tracks them in a separate validity mask, so an integer column with nulls stays an integer column. Pandas often converts such a column to floats instead.
NaN ("not a number") is different. It is an actual floating-point value, produced by operations like 0.0 / 0.0. Only float columns can contain it.
| Row | null | NaN |
|---|---|---|
| Meaning | The value is missing | The result is not a valid number |
| Dtypes | Any | Float only |
| Detected with | `is_null()` | `is_nan()` |
| Counted by `null_count()` | Yes | No |
| Skipped by `mean()` and `sum()` | Yes | No, it poisons the result |
The examples below use one DataFrame that contains both.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", None],
"salary": [120, None, 80, 90],
"bonus": [5.0, float("nan"), None, 2.0],
}
)
print(df.schema)
print(df.null_count())The schema shows salary as Int64, even though it holds a null. null_count() reports one null each for dept, salary and bonus. The NaN in bonus is not counted.
Detecting nulls
is_null() and is_not_null() return a boolean column. Use them to inspect or filter rows.
print(
df.select(
"name",
pl.col("salary").is_null().alias("salary_missing"),
pl.col("bonus").is_nan().alias("bonus_nan"),
)
)is_nan() returns null for a null input. A missing value is neither NaN nor a number.
How nulls propagate
Most operations return null when any input is null. The null does not raise an error and does not turn into zero.
print(df.select("name", (pl.col("salary") * 1.1).alias("raised")))Ben's raised value is null because his salary is null. Comparisons behave the same way: pl.col("salary") > 85 is null for Ben, not False.
Polars uses three-valued logic for boolean operators:
null & Falseis False, because the result is False whatever the null turns out to be.null | Trueis True, for the same reason.null & Trueandnull | Falseare null.
A filter keeps only rows where the predicate is True. Null counts as "not kept", so rows with unknown values disappear silently.
# Ben is dropped: his comparison is null, not True
print(df.filter(pl.col("salary") > 85))
# Keep rows that are high OR unknown
print(df.filter((pl.col("salary") > 85) | pl.col("salary").is_null()))Aggregations skip nulls
sum, mean, min, max and similar aggregations ignore nulls. pl.col(...).count() counts non-null values, while pl.len() counts all rows.
print(
df.select(
pl.col("salary").mean().alias("mean_salary"),
pl.col("salary").count().alias("non_null"),
pl.len().alias("rows"),
)
)The mean is the average of 120, 80 and 90. The count is 3 and the row count is 4.
NaN is not skipped. pl.col("bonus").mean() returns NaN, because one NaN makes the whole average undefined. Convert NaN to null first, and the aggregation behaves as you expect:
print(
df.select(
pl.col("bonus").mean().alias("with_nan"),
pl.col("bonus").fill_nan(None).mean().alias("nan_as_null"),
)
)The second column is 3.5, the mean of 5.0 and 2.0.
Replacing nulls
fill_null accepts a literal, an expression, or a strategy.
filled = df.with_columns(
pl.col("salary").fill_null(0).alias("salary_zero"),
pl.col("salary").fill_null(strategy="forward").alias("salary_ffill"),
pl.col("salary")
.cast(pl.Float64)
.fill_null(pl.col("salary").mean())
.alias("salary_mean"),
)
print(filled.select("name", "salary", "salary_zero", "salary_ffill", "salary_mean"))- A literal replaces every null with the same value.
strategy="forward"copies the previous non-null value down. Other strategies include"backward","min","max","mean"and"zero". Forward and backward fills depend on row order, so sort first if order carries meaning.- An expression can compute the replacement from the data. The cast to
Float64above keeps the column type consistent, because the mean is a float.
pl.coalesce returns the first non-null value across several expressions. It suits fallback chains:
print(
df.select(
"name",
pl.coalesce(pl.col("dept"), pl.lit("unassigned")).alias("dept_clean"),
)
)Replacing NaN is a separate step. fill_nan(None) turns NaN into null, and fill_null(0) can then replace those nulls.
Dropping rows with nulls
drop_nulls removes rows that contain a null. With no arguments it checks every column. With subset it checks only the columns you name.
print(df.drop_nulls())
print(df.drop_nulls(subset="salary"))Only Ana survives the first call, since every other row has a null somewhere. The second call keeps three rows. Prefer subset, because dropping on every column often removes rows you care about.
Nulls in conditions and comparisons
Equality comparisons also propagate nulls. pl.col("dept") == "eng" is null for Dee, and a filter on it drops her. For a null-safe comparison, use eq_missing and ne_missing, which treat null as an ordinary value.
print(
df.select(
"name",
(pl.col("dept") == "eng").alias("plain_eq"),
pl.col("dept").eq_missing("eng").alias("missing_eq"),
)
)when/then/otherwise has a similar trap. A null condition is treated as False, so the row falls through to otherwise. Ben's unknown salary would be labeled "standard" if you do not test for it first. Put the null case first:
banded = df.with_columns(
pl.when(pl.col("salary").is_null())
.then(pl.lit("unknown"))
.when(pl.col("salary") >= 100)
.then(pl.lit("high"))
.otherwise(pl.lit("standard"))
.alias("band")
)
print(banded.select("name", "salary", "band"))Nulls in grouping, sorting and joining
group_by: null is a valid key and forms its own group. Dee ends up in a group whosedeptis null.- Sorting: nulls come first in ascending order by default. Pass
nulls_last=Trueto move them to the end, as indf.sort("dept", nulls_last=True). - Joins: by default, null keys do not match each other. A row with a null join key finds no partner. In a left join it keeps its place and receives nulls from the right side.
print(
df.group_by("dept")
.agg(pl.col("salary").mean().alias("avg_salary"), pl.len().alias("headcount"))
.sort("dept", nulls_last=True)
)The eng group averages only Ana's 120, because Ben's null is skipped. Its headcount is still 2.
Choosing a strategy
The right handling depends on what the missing value means.
Filling with zero changes averages and totals in ways that may mislead. If "unknown" and "zero" mean different things, keep the null and handle it explicitly, as the band example does.
Exercises
Exercise
A DataFrame has a float column score with values 10.0, NaN and null. What does pl.col("score").mean() return, and how do you get 10.0 instead?
Show answer
It returns NaN, because the null is skipped but the NaN is a real float value that makes the mean undefined. Use pl.col("score").fill_nan(None).mean(). The NaN becomes null, the aggregation skips both missing values, and the mean is 10.0.
Exercise
You run df.filter(pl.col("dept") != "eng") on the chapter's DataFrame. Which names come back, and how would you also keep the row with a missing department?
Show answer
Only Cy comes back. Ana and Ben fail the test, and Dee's comparison is null, so the filter drops her. To keep Dee, use df.filter(pl.col("dept").ne_missing("eng")), or df.filter((pl.col("dept") != "eng") | pl.col("dept").is_null()).