Sub topic 16
Keeping work native: avoiding Python UDFs
This chapter assumes you can write expressions and use select, with_columns and filter. It also assumes you have seen when/then/otherwise and the lazy API.
What a Python UDF costs
A Python UDF (user-defined function) is a Python function that Polars calls on your data. The usual entry point is map_elements, which calls your function once per value.
Polars expressions run in compiled Rust code, across multiple threads, and the optimizer can see inside them. A UDF breaks all three:
- Each value is converted to a Python object, passed to your function, and converted back.
- The Python interpreter runs one thread at a time, so the work is not parallel.
- The optimizer cannot see inside the function. It cannot reorder it, push it down, or combine it with other steps.
Rewriting a UDF as an expression
Here is the same salary raise written both ways.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"salary": [120, 100, 80, 90],
}
)
slow = df.with_columns(
pl.col("salary")
.map_elements(lambda s: s * 1.1, return_dtype=pl.Float64)
.alias("raised")
)
fast = df.with_columns((pl.col("salary") * 1.1).alias("raised"))
print(slow.equals(fast))Both frames are equal. The second one stays native, so Polars can run it in parallel. For simple lambdas, Polars may emit a PolarsInefficientMapWarning that suggests the equivalent expression. Treat that warning as a prompt to rewrite.
Common replacements
Most UDFs fall into a few patterns that already have native forms.
| UDF habit | Native replacement |
|---|---|
| `lambda s: "high" if s >= 100 else "standard"` | `pl.when(...).then(...).otherwise(...)` |
| `lambda s: s.upper()` | `pl.col("name").str.to_uppercase()` |
| `lambda d: d.year` | `pl.col("date").dt.year()` |
| `lambda s: 0 if s is None else s` | `pl.col("salary").fill_null(0)` |
| Per-group Python loop | `group_by().agg(...)` or `.over(...)` |
The conditional case looks like this:
banded = df.with_columns(
pl.when(pl.col("salary") >= 100)
.then(pl.lit("high"))
.otherwise(pl.lit("standard"))
.alias("band")
)
print(banded)When a UDF is still the right tool
Sometimes no native expression exists, for example when you call a third-party library. Then keep the UDF as small as possible:
- Prefer
map_batches. It passes the whole Series to your function once, so the per-value overhead disappears. It works well with NumPy or other vectorized libraries. - If you must use
map_elements, always givereturn_dtype. Without it, Polars has to guess the output type from the results. - Do the native work first. Filter rows before the UDF, so it sees fewer values.
import numpy as np
result = df.with_columns(
pl.col("salary")
.map_batches(lambda s: s.map_elements(np.log1p, return_dtype=pl.Float64))
.alias("log_salary")
)
print(result)Exercise
A column price holds numbers. A colleague wrote pl.col("price").map_elements(lambda p: p * 2 if p > 10 else p, return_dtype=pl.Float64). Rewrite it natively and name one reason the native version is faster.
Show answer
Use pl.when(pl.col("price") > 10).then(pl.col("price") * 2).otherwise(pl.col("price")). It runs in compiled code across multiple threads and avoids converting every value to a Python object and back. The optimizer can also see through it.