Sub topic 8
Null versus NaN and missing data
This chapter assumes you know pandas missing-data handling (isna, fillna, dropna) and the basics of Polars expressions from earlier chapters. By the end you will know how Polars represents missing values, how its behavior differs from pandas, and how to port common cleaning code correctly.
Two different concepts
In pandas, missing data is a muddle. A float column uses NaN for missing values. An object column uses None or NaN. Nullable dtypes such as Int64 use pd.NA. The method isna() treats most of these as the same thing.
Polars separates two ideas:
- null is a missing value. It can appear in a column of any dtype, such as integers, strings, booleans or dates. It is stored in a validity bitmap, not in the data itself.
- NaN is "not a number". It is a legitimate floating-point value defined by IEEE 754. It exists only in float columns (
Float32andFloat64). It usually results from an invalid calculation, such as0.0 / 0.0.
A float column can contain both. They are different values, and different methods act on each.
import polars as pl
df = pl.DataFrame({"x": [1.0, None, float("nan")]})
print(
df.select(
pl.col("x").is_null().alias("is_null"),
pl.col("x").is_nan().alias("is_nan"),
pl.col("x").fill_null(0.0).alias("filled_null"),
)
)The output has three rows. is_null is true only for the second row. is_nan is true only for the third row, and it is null for the second row, because asking whether a missing value is NaN has no answer. fill_null(0.0) replaces only the second row. The NaN in the third row stays.
Method mapping
| pandas | Polars | Notes | Column |
|---|---|---|---|
| `s.isna()` | `pl.col("x").is_null()` | Does not catch NaN. | |
| `s.isna()` on floats with NaN | `is_null() \ | is_nan()` | Combine both on float columns. |
| `s.notna()` | `pl.col("x").is_not_null()` | Does not exclude NaN. | |
| `s.fillna(0)` | `fill_null(0)` and `fill_nan(0)` | Two separate operations. | |
| `s.ffill()` | `fill_null(strategy="forward")` | Strategies include `backward`, `min`, `max`, `mean`, `zero`, `one`. | |
| `df.dropna()` | `df.drop_nulls()` | Does not drop rows with NaN. | |
| `df.dropna(subset=["a"])` | `df.drop_nulls(subset="a")` | Accepts a name or list of names. |
Why it matters when porting
Reading data with pd.read_csv turns empty cells in float columns into NaN. pl.read_csv turns them into null. So a pipeline that called fillna in pandas and was ported to fill_nan in Polars would do nothing, because the empty cells are nulls. The correct call is fill_null.
import io
import polars as pl
csv = io.StringIO("price,qty\n10.0,2\n,3\n7.5,\n")
df = pl.read_csv(csv)
print(df.null_count())
print(df.with_columns(pl.col("price").fill_null(0.0)))null_count() reports one null in each column. Because integer columns can hold nulls, qty stays an integer dtype. In pandas, a missing value would have forced that column to float.
The reverse also happens. If a calculation produces NaN, drop_nulls will keep the row. Check for NaN explicitly:
import polars as pl
df = pl.DataFrame({"a": [1.0, 0.0, None], "b": [2.0, 0.0, 3.0]})
ratio = df.with_columns((pl.col("a") / pl.col("b")).alias("ratio"))
print(ratio)
print(ratio.filter(pl.col("ratio").is_not_nan()))Here 0.0 / 0.0 gives NaN. Note that filter(is_not_nan()) also drops the row whose ratio is null. A null filter result is treated as false, so that row is excluded.
Nulls propagate, and comparisons with null are null
Arithmetic with a null gives null. A comparison with a null gives null, not False. In filter, a null result removes the row.
import polars as pl
df = pl.DataFrame({"v": [1, None, 3]})
print(df.filter(pl.col("v") != 1))Only the row with 3 remains. The null row is dropped, even though a null is "not equal to 1" in everyday terms. If you want to keep nulls, say so:
print(df.filter((pl.col("v") != 1) | pl.col("v").is_null()))To compare with nulls treated as ordinary values, use eq_missing and ne_missing:
print(df.select(pl.col("v").eq_missing(None).alias("v_is_missing")))In pandas, NaN != 1 is True, so a ported filter can silently lose rows. Review each comparison on a column that may contain missing data.
NaN comparisons and ordering
Polars treats NaN as equal to itself in comparisons, and orders it as larger than every other number. This differs from IEEE 754 and from pandas, where NaN == NaN is False. It makes grouping, joining and sorting on float columns predictable, but it means you cannot find NaN with == float("nan") in pandas style. Use is_nan(), which states the intent.
Aggregations skip nulls, not NaN
Aggregations such as sum, mean, min and max ignore nulls. This matches pandas' default skipna=True. NaN is different: it is a real value, so it contaminates sum and mean.
import polars as pl
df = pl.DataFrame({"x": [1.0, None, 3.0], "y": [1.0, float("nan"), 3.0]})
print(
df.select(
pl.col("x").mean().alias("mean_x"),
pl.col("y").mean().alias("mean_y"),
pl.col("x").count().alias("count_x"),
pl.len().alias("rows"),
)
)mean_x is 2.0. mean_y is NaN. count_x is 2, because count counts non-null values. pl.len() is 3, the number of rows. This distinction replaces the pandas split between count() and size().
If you want NaN treated as missing before aggregating, convert it first:
cleaned = df.with_columns(pl.col(pl.Float64).fill_nan(None))
print(cleaned.select(pl.col("y").mean()))fill_nan(None) turns NaN into null. After that, the regular null-aware tools work. Many pipelines normalize this way once, right after loading.
Booleans and other dtypes
Because null is available in every dtype, boolean columns can be three-valued: true, false or null. Polars follows three-valued logic. null & False is False, and null | True is True, but null & True is null. A when/then/otherwise condition that evaluates to null falls through to otherwise.
Strings are also straightforward. A missing string is null, not the text "nan" or None in an object column. Use is_null() and fill_null("unknown").
Migration checklist
- Replace
isna,notna,fillnaanddropnawith their null-based counterparts. - On float columns that may hold NaN from calculations, decide whether NaN means "missing". If so, call
fill_nan(None)once after the calculation. - Review every
!=,<and>filter on nullable columns. Add| is_null()or usene_missingwhere rows should be kept. - Replace
count()/size()logic withcount()(non-null values) andpl.len()(rows). - Expect integer columns with gaps to stay integers, and update downstream code that assumed float.
Exercise
A pandas script does df["price"].fillna(0) after read_csv. A colleague ports it to df.with_columns(pl.col("price").fill_nan(0)) and finds the empty cells are still empty. Why, and what is the fix?
Show answer
pl.read_csv reads empty cells as null, not NaN, and fill_nan only changes NaN values. Use pl.col("price").fill_null(0). If the column may also contain NaN from calculations, add .fill_nan(0) as well, or call fill_nan(None) first and then fill_null(0).
Exercise
Given df = pl.DataFrame({"v": [1, None, 3]}), what does df.filter(pl.col("v") != 1) return, and how do you keep the null row too?
Show answer
It returns only the row with 3, because None != 1 evaluates to null and filter drops rows where the predicate is not true. To keep the null row, use df.filter((pl.col("v") != 1) | pl.col("v").is_null()), or df.filter(pl.col("v").ne_missing(1)).