Sub topic 15
Replacing apply and row iteration with expressions
This chapter assumes you know the Polars expression model from earlier chapters: pl.col, with_columns, and when/then/otherwise.
Why apply is the first thing to remove
In pandas, df.apply(func, axis=1) and iterrows() call a Python function once per row. Each call pays Python overhead, cannot run in parallel, and is invisible to any optimizer. Polars expressions run in compiled code across whole columns and use multiple threads. Most row-wise logic can be rewritten as column arithmetic plus a condition.
Common rewrites
| pandas pattern | Polars replacement |
|---|---|
| `apply(lambda r: r["a"] * r["b"], axis=1)` | `pl.col("a") * pl.col("b")` |
| `apply` with `if/else` per row | `pl.when(...).then(...).otherwise(...)` |
| `Series.map(dict)` | `replace_strict(mapping, default=...)` |
| `Series.apply(str_func)` | `.str` namespace methods |
| `for _, row in df.iterrows()` | one expression, or `group_by` and `agg` |
Worked example
The pandas version below computes a discounted total with a row-wise function. It also maps region codes to names.
import pandas as pd
pdf = pd.DataFrame(
{
"price": [10.0, 20.0, 5.0],
"qty": [12, 3, 20],
"region": ["N", "S", "E"],
}
)
pdf["total"] = pdf.apply(
lambda r: r["price"] * r["qty"] * (0.9 if r["qty"] >= 10 else 1.0),
axis=1,
)
pdf["region_name"] = pdf["region"].map({"N": "North", "S": "South"}).fillna("Other")In Polars, the condition becomes an expression, and the mapping becomes replace_strict with a default.
import polars as pl
df = pl.DataFrame(
{
"price": [10.0, 20.0, 5.0],
"qty": [12, 3, 20],
"region": ["N", "S", "E"],
}
)
df = df.with_columns(
(
pl.col("price")
* pl.col("qty")
* pl.when(pl.col("qty") >= 10).then(0.9).otherwise(1.0)
).alias("total"),
pl.col("region")
.replace_strict({"N": "North", "S": "South"}, default="Other")
.alias("region_name"),
)
print(df)Both new columns are computed in one with_columns call, so Polars can evaluate them in parallel.
When no expression exists
Some logic really is arbitrary Python, such as a call into a third-party parser. Use map_elements and declare the output type.
import re
def slugify(text: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
names = pl.DataFrame({"title": ["Hello, World!", "Polars 101"]})
names = names.with_columns(
pl.col("title").map_elements(slugify, return_dtype=pl.String).alias("slug")
)
print(names)Replacing iterrows
Loops that build up a result row by row usually fit one of three shapes:
- Row-local math. Use column expressions.
- Running totals or per-group values. Use
cum_sum()orover(). - Collecting rows per key. Use
group_by().agg().
If you must hand rows to non-Polars code, use df.iter_rows(named=True) or df.to_dicts(). Do this only at the edge of your pipeline.
Exercise
A pandas column is built with df["flag"] = df.apply(lambda r: "high" if r["score"] > 80 and r["active"] else "low", axis=1). Write the Polars equivalent.
Show answer
df = df.with_columns(pl.when((pl.col("score") > 80) & pl.col("active")).then(pl.lit("high")).otherwise(pl.lit("low")).alias("flag")). Use & instead of the Python keyword and, and wrap the string constants in pl.lit.