Sub topic 16
Keeping work native: avoiding Python UDFs
This chapter assumes you know the expression contexts (select, with_columns, filter, group_by), when/then/otherwise, and the basic lazy API. Examples use the df from earlier chapters and a recent Polars 1.x release.
What a UDF is and why it costs so much
A user-defined function (UDF) is a Python function that you hand to Polars so it can run on your data. The two main entry points are:
Expr.map_elements(function, return_dtype=...)calls your function once per value.Expr.map_batches(function, return_dtype=...)calls your function once per column, passing a wholeSeries.
Native expressions, such as pl.col("salary") * 1.1, are compiled Rust code. Polars runs them across threads, on contiguous memory, without touching the Python interpreter. A UDF breaks all three properties.
- Per-row interpreter calls.
map_elementsconverts each value to a Python object, calls your function, and converts the result back. The call overhead is paid for every row. - The GIL. Python code holds the Global Interpreter Lock, so Polars cannot spread UDF work across cores.
- An opaque step for the optimizer. In a lazy query, the optimizer can reorder and prune native expressions. It cannot see inside a Python function, so it cannot reason about what the function reads or produces.
The pandas apply habit is the usual source of UDFs in Polars code. Treat a UDF as a last resort.
Measuring the gap
This script times the same predicate written both ways on a million rows.
import time
import polars as pl
df = pl.DataFrame({"x": range(1_000_000)})
start = time.perf_counter()
with_udf = df.with_columns(
pl.col("x")
.map_elements(lambda v: v % 7 == 0, return_dtype=pl.Boolean)
.alias("flag")
)
udf_seconds = time.perf_counter() - start
start = time.perf_counter()
native = df.with_columns((pl.col("x") % 7 == 0).alias("flag"))
native_seconds = time.perf_counter() - start
print(with_udf.equals(native))
print(f"udf: {udf_seconds:.3f}s native: {native_seconds:.3f}s")The two results are equal. The native version is typically one to two orders of magnitude faster, though the exact ratio depends on your machine.
Polars also tries to help. When a map_elements lambda is simple enough to analyze, Polars emits a PolarsInefficientMapWarning that suggests the equivalent native expression. Treat that warning as a to-do item, not as noise to silence.
Rewriting common UDFs as expressions
Most UDFs exist because the author did not know the matching expression. The table lists frequent cases.
| Python habit inside a UDF | Native expression |
|---|---|
| `"high" if s >= 100 else "standard"` | `pl.when(...).then(...).otherwise(...)` |
| `s.upper()`, `s.startswith("a")` | `.str.to_uppercase()`, `.str.starts_with("a")` |
| `d.year`, `d.weekday()` | `.dt.year()`, `.dt.weekday()` |
| `0 if v is None else v` | `.fill_null(0)` |
| `{"eng": 3, "ops": 1}.get(v, 0)` | `.replace_strict(mapping, default=0)` |
| A function that reads two columns of a row | An expression that combines both `pl.col(...)` calls |
| A loop that keeps a running total | `.cum_sum()` |
| A loop that compares with the previous row | `.shift(1)` or `.diff()` |
The next example takes three UDFs and replaces each with an expression.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
floors = {"eng": 3, "ops": 1}
# Three UDFs
udf_version = df.with_columns(
pl.col("name").map_elements(lambda s: s.upper(), return_dtype=pl.String).alias("shout"),
pl.col("dept").map_elements(lambda d: floors.get(d, 0), return_dtype=pl.Int64).alias("floor"),
pl.col("salary")
.map_elements(lambda s: "high" if s >= 100 else "standard", return_dtype=pl.String)
.alias("band"),
)
# The same result with native expressions
native_version = df.with_columns(
pl.col("name").str.to_uppercase().alias("shout"),
pl.col("dept").replace_strict(floors, default=0, return_dtype=pl.Int64).alias("floor"),
pl.when(pl.col("salary") >= 100)
.then(pl.lit("high"))
.otherwise(pl.lit("standard"))
.alias("band"),
)
print(udf_version.equals(native_version))
print(native_version)For the dictionary lookup there is a second option. If the mapping is large or lives in a file, put it in a DataFrame and use a left join, as shown in the joins chapter. A join also keeps the lookup visible to the optimizer.
Multi-column logic needs no struct
A common workaround is to pack several columns into a struct and write pl.struct(...).map_elements(lambda row: ...). Each row then arrives as a dictionary. Nearly always the better choice is to write the logic directly with several pl.col calls inside one expression.
bonus = df.with_columns(
pl.when(pl.col("dept") == "eng")
.then(pl.col("salary") * 0.10)
.otherwise(pl.col("salary") * 0.05)
.alias("bonus")
)
print(bonus)Expressions are column-wise, so every pl.col(...) inside one expression lines up row by row. You do not need a row object.
A decision path
When you reach for a UDF, work through these questions in order.
When a UDF is justified
Some work has no native form. Examples are calling a third-party library for each value, parsing a custom binary format, or applying a numerical routine that Polars does not implement. Two rules keep the cost down.
- Prefer
map_batchesovermap_elements. It calls your function once per column, so the per-row Python overhead disappears if the function is vectorized. - Always pass
return_dtype. Without it, Polars must guess the output type, and it warns that the guess may be wrong.
This example applies a NumPy function that Polars has no expression for.
import numpy as np
import polars as pl
df = pl.DataFrame({"salary": [120, 100, 80, 90]})
def sinc_series(s: pl.Series) -> pl.Series:
return pl.Series(s.name, np.sinc(s.to_numpy() / 100))
out = df.with_columns(
pl.col("salary").map_batches(sinc_series, return_dtype=pl.Float64).alias("sinc")
)
print(out)The function runs once and NumPy does the loop in C. This is much faster than map_elements with np.sinc on a scalar. Recent Polars versions also accept is_elementwise=True on map_batches. It promises the optimizer that output row i depends only on input row i, which lets the function take part in more optimizations. Set it only when the promise holds.
Gotchas
- Nulls are skipped by default.
map_elementshasskip_nulls=True, so your function never sees a null and the output stays null at that position. This is convenient, but it differs from a function that handlesNoneitself. If you want to map nulls to a value, callfill_nullbefore or after, or setskip_nulls=Falseand handleNonein the function. - Types are your responsibility. If the function returns a value that does not match
return_dtype, you get an error or a silently changed column. A native expression has its output type inferred from its inputs. - Lazy queries lose optimizations. A UDF is a barrier in the plan. Filters that depend on a UDF column cannot move below it, and the engine cannot always process the step in streaming mode. Apply native filters first, so the UDF sees fewer rows.
- Group contexts behave differently. Inside
group_by(...).agg(...)orover(...), a UDF runs on group data, not on the full column. Test with a small frame, and prefer a native aggregation whenever one exists. - Errors are harder to read. An exception inside a UDF surfaces through Polars' execution layer. A native expression fails with a schema or type error that names the column.
Exercises
Exercise
A colleague wrote df.with_columns(pl.col("salary").map_elements(lambda s: s * 1.1, return_dtype=pl.Float64).alias("raised")). Rewrite it natively and name two reasons the original is slower.
Show answer
Use df.with_columns((pl.col("salary") * 1.1).alias("raised")). The UDF is slower because it calls the Python interpreter once per row, and because it holds the GIL so Polars cannot run it on several threads. It is also opaque to the optimizer.
Exercise
You must apply a NumPy function with no Polars equivalent to a column. Which entry point should you choose, and which argument should you always supply?
Show answer
Use map_batches, so the function runs once on the whole Series and NumPy does the looping. Always supply return_dtype, so Polars does not have to guess the output type.
Exercise
A map_elements function returns 0 when it receives None, yet the output contains nulls where the input was null. Why, and how do you fix it?
Show answer
map_elements defaults to skip_nulls=True, so the function never sees the nulls and they pass through unchanged. Fix it by replacing the UDF with pl.col("x").fill_null(0) and the real transformation, or by setting skip_nulls=False and handling None inside the function.