Polars is fast because it runs expressions in compiled code on whole columns. The moment you hand it a Python function, that speed is traded for flexibility. Knowing the ladder of options, and stopping on the lowest rung that does the job, is what keeps a pipeline fast.
The idea in plain words
Where we are. Topics 1 to 9 stayed with built-in expressions. This one is about the four ways to go beyond them. Compose your own expression in a function, which costs nothing. Call Python on every value with map_elements, which is the slow last resort. Aggregate to lists and use plain Python once per group. And register a namespace so that your own expressions read like built-ins.
Your own Python function used inside a query. Polars cannot look inside it or optimize it, and calls it once per value or group from compiled code, which is why it is slower than a built-in expression that does the same work.
Your own expression, at full speed
An expression is a value in Python: you can build it in a function and return it. zscore_expr("close", 20) is nothing but a recipe made of rolling_mean and rolling_std, so Polars optimizes and runs it like any built-in. The caller adds .over("symbol") and .alias(...), which is why the function returns an expression and not a frame. This is the first thing to reach for, and it covers most reuse.
# A reusable expression: the caller decides the window per symbol and the nameexpr = zscore_expr("close", 20)print(type(expr).__name__)z = bars.with_columns(expr.over("symbol").alias("z20"))latest = z.group_by("symbol").agg(pl.col("z20").last()).sort("symbol")print([(s, round(v, 2)) for s, v in latest.rows()])
Expr
[('AAPL', -0.41), ('JNJ', 1.44), ('JPM', -1.04), ('KO', 2.05), ('XOM', 1.5)]Python on every value: the slow rung
map_elements(fn, return_dtype=...) calls your function for each value and collects the results. It can do anything Python can do, such as call a library or run a branch of if statements, at the price of a Python call per value, often fifty to a hundred times slower. Always say return_dtype, so Polars does not have to guess, and check first whether a built-in does the same, as with the square root below.
# The same square root by Python function and by built-in expression: the same numbers, very different costby_python = apply_python(bars, "close", lambda x: x ** 0.5).get_column("close_py")built_in = bars.select(pl.col("close").sqrt()).get_column("close")print("same to 1e-9:", max(abs(a - b) for a, b in zip(by_python, built_in)) < 1e-9, "| values:", by_python.len())
same to 1e-9: True | values: 33493
Python once per group, and your own namespace
Some logic is naturally sequential, such as the longest run of rising days: each step depends on the one before. Aggregate each symbol's closes into a list with group_by(...).agg(pl.col("close")), and loop over those few lists in plain Python. That is five Python loops instead of thirty-three thousand calls. When you have an expression you use everywhere, pl.api.register_expr_namespace("qc") on a small class makes it callable as pl.col("close").qc.drawdown(), which reads exactly like a built-in and is still fully optimized, because it only composes expressions.
# Python once per symbol on aggregated lists, then a namespace that reads like a built-inprint(longest_up_streaks(bars).rows())register_namespace("qc")worst = bars.select(pl.col("close").qc.drawdown().over("symbol").alias("dd")).get_column("dd").min()print("deepest drawdown of any stock:", round(worst, 3))
[('AAPL', 12), ('JNJ', 13), ('JPM', 10), ('KO', 10), ('XOM', 11)]
deepest drawdown of any stock: -0.818Ask in this order: can built-in expressions do it? Can I compose them in a function? Does the logic work on one list per group? Only then use map_elements. Each rung up costs speed, and a Python function is also invisible to the optimizer, so it cannot be pushed down into a scan.
What the tasks ask
- 1`zscore_expr` and `apply_python`Return
(col - col.rolling_mean(w)) / col.rolling_std(w)as an expression;with_columns(pl.col(name).map_elements(fn, return_dtype=pl.Float64).alias(f"{name}_py")). - 2`longest_up_streaks` and `register_namespace`
group_by("symbol", maintain_order=True).agg(pl.col("close")), a plain loop per list, a frame of results;@pl.api.register_expr_namespace(name)on a class that keepsself._expr.
Lab · what's graded
4 tasks · 100 pts- Your own expression:
zscore_expr25 pts - Python on every value:
apply_python25 pts - Python on aggregated lists:
longest_up_streaks25 pts - A namespace of your own:
register_namespace25 pts