Sub topic 5
Polars: a fast DataFrame engine with a lazy API
This chapter assumes you know basic Python, can load and transform a table with pandas or SQL, and have read the earlier chapters on eager and lazy execution and on Parquet and Arrow. Here you will build a working model of Polars, learn its two APIs, and see the errors people commonly hit when coming from pandas.
What Polars is
Polars is a DataFrame library written in Rust with a Python API. It runs on a single machine and uses all CPU cores by default. It stores data in a columnar layout that follows the Apache Arrow memory format, so a column is a contiguous block of values of one type. It has no row index. Rows are identified only by position.
Polars offers two ways to work:
- Eager API.
pl.DataFrameandpl.read_parquetrun each operation immediately, much like pandas. - Lazy API.
pl.LazyFrameandpl.scan_parquetrecord your operations as a query plan. Nothing runs until you callcollect(). Before running, Polars optimizes the plan.
The lazy API is where Polars is strongest, and it is the one to learn first.
Expressions: the core idea
Polars code is built from expressions. An expression describes a computation on columns, such as pl.col("revenue") * 2. It is not tied to a particular DataFrame until you pass it to a method like select, with_columns, filter, or agg.
import polars as pl
df = pl.DataFrame(
{
"region": ["eu", "us", "eu", "us", "eu"],
"revenue": [10.0, 20.0, 5.0, -3.0, 12.5],
}
)
out = (
df.filter(pl.col("revenue") > 0)
.with_columns((pl.col("revenue") * 1.2).alias("revenue_with_tax"))
.group_by("region")
.agg(
pl.col("revenue").sum().alias("total"),
pl.col("revenue_with_tax").mean().alias("avg_with_tax"),
pl.len().alias("rows"),
)
.sort("region")
)
print(out)Several things differ from pandas:
with_columnsreturns a new DataFrame. Polars does not modify a DataFrame in place, and there is nodf["x"] = ...assignment style.aggaccepts several expressions, and each runs in parallel.pl.len()counts rows in a group. Older code may usepl.count(), which has been replaced in recent versions.- Names such as
group_byreplaced the oldergroupby. If code from an old tutorial fails with an attribute error, check the version.
Lazy execution and the query plan
With scan_parquet, Polars does not read the file at that point. It builds a plan. When you call collect(), an optimizer rewrites the plan and then the engine runs it.
Two optimizations matter most for Parquet data:
- Projection pushdown. Only the columns the query uses are read from the file.
- Predicate pushdown. Filters are pushed into the scan, so Parquet row groups whose statistics show they cannot match can be skipped.
You can see the plan before running anything with explain().
import polars as pl
lf = (
pl.scan_parquet("sales.parquet")
.filter(pl.col("revenue") > 0)
.select("region", "revenue")
)
print(lf.explain())In the printed plan, look at the scan node. It should list the selected columns and the filter condition, which shows the pushdown happened. If your plan shows a filter sitting above a full scan, the filter was written in a way the optimizer could not push down. A common cause is applying a Python function with map_elements, which the optimizer treats as opaque.
Other optimizations include combining repeated sub-expressions and reusing results. The effect depends on the query, so check explain() instead of assuming.
Lazy versus eager in practice
Use the eager API for small data, quick exploration in a notebook, and cases where you want to see intermediate results. Use the lazy API for pipelines that read files, because only the lazy form can skip data it does not need.
You can switch between them. df.lazy() turns a DataFrame into a LazyFrame, and lf.collect() turns it back. A reasonable pattern is to scan, build the whole query, and call collect() once at the end, instead of collecting in the middle and continuing in eager mode. Each early collect() ends the optimization window.
Larger-than-memory work
Polars can process data larger than RAM with its streaming engine. You request it at collection time:
import polars as pl
result = (
pl.scan_parquet("sales.parquet")
.group_by("region")
.agg(pl.col("revenue").sum())
.collect(engine="streaming")
)
print(result)The streaming engine processes data in batches. Two limits apply:
- Not every operation is supported in streaming mode, and the set has changed between releases. Unsupported operations may fall back to the in-memory engine, so a query can still run out of memory.
- The final result must fit in memory. A group-by with a handful of groups is fine. A query that returns most of a billion-row table is not.
The engine="streaming" argument exists in recent releases. Older releases used streaming=True. Check your installed version if one form raises an error. For files that are far larger than memory and for complex joins, test with your own data before relying on streaming. The memory chapter later in this tutorial covers how to estimate this.
Common errors for pandas users
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError` on `df["a"] = ...` | Polars DataFrames do not support item assignment | Use `df.with_columns(... .alias("a"))` |
| Code runs but nothing seems to happen | A LazyFrame was built but never collected | Call `collect()` |
| `ColumnNotFoundError` after `select` | `select` keeps only the listed columns | Use `with_columns` to add columns while keeping the rest |
| Slow query with `map_elements` | A Python function runs per value and blocks optimization | Rewrite with built-in expressions such as `pl.when().then().otherwise()` |
| `SchemaError` or type mismatch on join | Join keys have different dtypes, for example `Int32` and `Int64` | Cast with `.cast()` before joining |
| Surprising nulls versus NaN | Polars distinguishes null (missing) from NaN (a float value) | Use `is_null()` and `fill_null()` for missing data, and `is_nan()` for NaN |
Two further points:
- Polars is strict about types. Mixing a string and an integer in one column raises an error, where pandas would make an
objectcolumn. - Row order is not guaranteed after some operations.
group_byreturns groups in no fixed order unless you passmaintain_order=Trueor sort afterwards. Always sort if the output order matters.
Strengths and limits
Strengths:
- Multi-core execution by default, with no setup.
- A lazy optimizer that cuts the data read from Parquet.
- Consistent, readable expression syntax.
- Strict types and explicit nulls, which catch bugs early.
Limits:
- Single machine only. There is no cluster mode in the open-source library.
- The streaming engine does not cover every operation.
- The API has changed across releases, so pin your version in production and read the changelog before upgrading.
- Fewer integrations than pandas. Some plotting, statistics, and machine learning libraries expect pandas objects, so you may call
to_pandas()at the boundary. This conversion needspyarrowand copies data in many cases. - SQL users may prefer DuckDB. Polars does have a SQL interface, but its main design is the expression API.
Summary of what to remember
- Polars is a single-node, multi-core, columnar DataFrame engine.
- Write expressions, and prefer
scan_*pluscollect()for file-based pipelines. - Use
explain()to check that projection and predicate pushdown happened. - Streaming extends reach beyond RAM, but verify it on your own query.
- Avoid per-row Python functions, because they block optimization and run slowly.
Exercise
A colleague writes pl.scan_parquet("events.parquet").filter(pl.col("country") == "DE").select("user_id").collect() and says it reads the whole file into memory first and then filters. What would you check with explain(), and what result would show they are wrong?
Show answer
Call explain() on the LazyFrame before collect(). If the scan node lists only the user_id and country columns and shows the country == "DE" condition as part of the scan (projection and predicate pushdown), Polars is reading only those columns and skipping row groups that cannot match. That shows the file is not read fully and then filtered.
Exercise
You have a Polars query that groups 2 billion rows by customer_id, producing about 300 million groups, and it runs out of memory even with collect(engine="streaming"). Give two reasons this can happen and one alternative.
Show answer
First, the result has 300 million groups, so the final table, and the intermediate group state, may not fit in memory. Second, an operation in the query may not be supported by the streaming engine, so Polars falls back to the in-memory engine. An alternative is to run the aggregation in DuckDB, which can spill to disk, or in Spark if the data needs several machines. You could also reduce the result by filtering or partitioning the data by key ranges and processing each part separately.