Sub topic 15
Replacing apply and row iteration with expressions
This chapter assumes you can write pandas apply(axis=1) and iterrows loops. It also assumes you know pl.col, with_columns and filter from the earlier chapters. Polars 1.0 or later is assumed, because replace_strict was added in that line.
Why apply is the first thing to remove
In pandas, df.apply(func, axis=1) calls a Python function once per row. Each call builds a row object, runs interpreted code and returns a Python value. iterrows has the same cost.
Polars expressions are different. An expression such as pl.col("price") * pl.col("qty") is a description of work. Polars compiles it to native code, runs it on whole columns, and can spread it across threads. The lazy optimizer can also reorder it.
The Polars counterpart of apply is map_elements. It calls Python once per value, so it keeps the slow part of pandas. The optimizer also cannot see inside your function. Treat map_elements as the last resort, not the default translation.
Translation table
| pandas pattern | Polars expression |
|---|---|
| `apply(axis=1)` with arithmetic | Arithmetic on `pl.col(...)` |
| `if` / `elif` / `else` in a function | `pl.when().then().otherwise()` |
| `Series.map(dict)` | `replace_strict(mapping, default=...)` |
| `Series.apply(str_function)` | `.str.*` methods |
| `iterrows` using the previous row | `shift`, `diff`, `pct_change` |
| Running totals in a loop | `cum_sum`, `cum_max`, `cum_min` |
| Windowed loops | `rolling_mean`, `rolling_sum` |
Branching logic becomes when/then/otherwise
The pandas version below calls a function for every row. The Polars version states the same rules as one expression.
import pandas as pd
import polars as pl
data = {
"price": [30.0, 40.0, 5.0],
"qty": [2, 5, 1],
"country": ["US", "DE", "US"],
}
# pandas
pdf = pd.DataFrame(data)
def shipping(row):
if row["country"] != "US":
return 9.99
if row["price"] * row["qty"] > 50:
return 0.0
return 4.99
pdf["shipping"] = pdf.apply(shipping, axis=1)
# Polars
df = pl.DataFrame(data)
total = pl.col("price") * pl.col("qty")
df = df.with_columns(
pl.when(pl.col("country") != "US").then(9.99)
.when(total > 50).then(0.0)
.otherwise(4.99)
.alias("shipping")
)
print(df)The when branches are checked in order, like if and elif. Reusing total shows that expressions are ordinary Python objects. You can store one in a variable and combine it with others.
Note these points about when:
- Without
otherwise, rows that match no branch get null. - Python's
if,and,orandnotdo not work on expressions. Use&,|and~, and put each comparison in parentheses. - Polars computes every branch for the whole column. Nothing short-circuits per row.
Dictionary lookups become replace_strict
pandas code often maps codes to labels with Series.map(dict), and unmapped values turn into NaN. replace_strict raises an error for unmapped values unless you give a default, which makes missing keys easier to notice.
import pandas as pd
import polars as pl
labels = {"US": "North America", "CA": "North America", "DE": "Europe"}
countries = ["US", "DE", "BR"]
# pandas
pdf = pd.DataFrame({"country": countries})
pdf["area"] = pdf["country"].map(labels).fillna("Other")
# Polars
df = pl.DataFrame({"country": countries})
df = df.with_columns(
pl.col("country").replace_strict(labels, default="Other").alias("area")
)
print(df)If you want to change a few values and leave the rest alone, use replace. It does not require every value to be in the mapping.
String logic uses namespaces
A pandas apply(lambda s: s.strip().upper()) has a native equivalent. Look in the str namespace before writing a function.
import polars as pl
df = pl.DataFrame({"sku": [" ab-12", "CD 34 ", None]})
df = df.with_columns(
pl.col("sku")
.str.strip_chars()
.str.to_uppercase()
.str.replace_all(r"[^A-Z0-9]", "")
.alias("sku_clean")
)
print(df)The null stays null, and no extra code handles it. Date logic works the same way through the dt namespace, for example pl.col("ts").dt.month().
Row loops that look at previous rows
A loop that remembers the previous row feels like it needs iteration. It usually does not.
import pandas as pd
import polars as pl
closes = {"day": [1, 2, 3, 4], "close": [100.0, 102.0, 99.0, 105.0]}
# pandas loop
pdf = pd.DataFrame(closes)
returns, prev = [], None
for _, row in pdf.iterrows():
returns.append(None if prev is None else row["close"] / prev - 1)
prev = row["close"]
pdf["ret"] = returns
# Polars expressions
df = pl.DataFrame(closes).with_columns(
(pl.col("close") / pl.col("close").shift(1) - 1).alias("ret"),
pl.col("close").cum_max().alias("running_high"),
pl.col("close").rolling_mean(window_size=2).alias("avg_2d"),
)
print(df)shift(1) moves the column down one row, so each row sees the previous value. The first row of ret is null, where pandas would hold NaN. Polars has a built-in pct_change for this exact case. A true recurrence, where each value depends on a value your own loop just computed, is one of the few cases that may still need Python or a cum_* trick.
When map_elements is justified
Sometimes you must call a Python function, such as one from a library with no Polars equivalent. Give map_elements a return_dtype. Without it, Polars must guess the output type from the results. To pass several columns, combine them with pl.struct. The function then receives a dict for each row.
import math
import polars as pl
df = pl.DataFrame({"dx": [3.0, 5.0], "dy": [4.0, 12.0]})
df = df.with_columns(
pl.struct("dx", "dy")
.map_elements(lambda r: math.hypot(r["dx"], r["dy"]), return_dtype=pl.Float64)
.alias("dist_python"),
(pl.col("dx") ** 2 + pl.col("dy") ** 2).sqrt().alias("dist_native"),
)
print(df)Both columns match, but only dist_native runs without per-row Python calls. Two behaviors to remember:
- By default,
map_elementsskips nulls and returns null for them, so your function never seesNone. - It does not run in parallel across rows, because the Python interpreter is involved on each call.
Before you keep a map_elements call, ask whether its logic fits when/then, replace_strict, a namespace method or a window function.
Common errors
TypeErroroniforand: you used Python boolean operators on expressions. Use&,|and~.- Unexpected nulls from
when: you left outotherwise. replace_strictfails: some values are missing from the mapping. Adddefault=or complete the mapping.- Slow
map_elements: the function runs once per value. Search for a native expression first.
Exercise
This pandas code labels each row: df["tier"] = df.apply(lambda r: "gold" if r["spend"] >= 1000 else ("silver" if r["spend"] >= 100 else "bronze"), axis=1). Write the Polars translation using with_columns, and say why it is faster than keeping the lambda in map_elements.
Show answer
Use df.with_columns(pl.when(pl.col("spend") >= 1000).then(pl.lit("gold")).when(pl.col("spend") >= 100).then(pl.lit("silver")).otherwise(pl.lit("bronze")).alias("tier")). It is faster because the whole condition is evaluated on columns in native code and the optimizer can see it. A map_elements call would run the Python lambda once per row.