Polars from zero to expert: the complete guide to the Rust data framework
Complete Polars guide in Python: expressions, lazy API, streaming, IO, joins, window functions, and performance from zero to expert.
Table of Contents
Imagine you analyze data with pandas and everything works until the file grows. One day your CSV goes from 500 MB to 8 GB, read_csv takes four minutes, RAM hits 95%, and the laptop starts swapping. You move to a bigger machine, it works for a week, and the dataset grows again.
The problem is not the machine. It is that pandas was designed for data that fits in memory, on a single thread, with data types that do not take advantage of modern hardware. Polars was born for the opposite problem: datasets that do not fit in RAM, 16-core CPUs, and queries that must run in milliseconds, not minutes.
This guide is a journey from zero to expert. It is not a summary of the documentation: it is the path I wish I had when I started, with runnable code, expected output, and the traps that cost hours of debugging. By the end you will understand not only how to write Polars, but why the engine executes your queries the way it does.
What Polars is and why it matters
Polars is a DataFrame library and an analytical query engine written in Rust. It is not a pandas wrapper or a thin layer over NumPy: it is a complete engine with its own optimizer, columnar format, and execution planner.
The philosophy
According to its official documentation, Polars has five goals:
- Use all available cores on the machine.
- Optimize queries to reduce work and memory allocations.
- Handle datasets larger than available RAM.
- Offer a consistent and predictable API.
- Adhere to a strict schema: data types are known before running the query.
That last line is the cultural difference from pandas. In pandas, a column can have mixed types and the system tolerates it (until it does not). In Polars, the schema is strict and validated before execution. That enables optimization, parallelization, and early error detection.
The technical pieces
- Rust: the core is written in Rust, without heavy external dependencies. C/C++-level performance with memory safety.
- Apache Arrow: the in-memory columnar format. Polars has its own compute and buffer implementation, but is Arrow-compatible for zero-copy interoperability.
- Vectorized, multi-threaded engine: operations run on entire columns, not row by row, and are spread across cores without configuration.
- Query optimizer: when you use the lazy API, Polars rewrites the plan to read less data and do less work.
- Streaming: it can process datasets that do not fit in RAM, in batches.
- Optional GPU: with the
gpuextra, some queries run on NVIDIA GPUs.
Polars vs pandas: what actually changes
| Aspect | pandas | Polars |
|---|---|---|
| Execution | Single-threaded (mostly) | Multi-threaded by default |
| Memory | Loads everything into RAM | Lazy + streaming, can avoid loading everything |
| Types | Flexible inference, objects for strings | Strict schema, Arrow |
| API | Imperative, mutable | Composable expressions, immutable |
| Optimization | Limited | Full query optimizer |
| Data > RAM | Requires Dask/Spark | Native streaming |
Polars is not “pandas but faster.” It is a change of mental model: you stop saying “do this, then that” and start describing “what I want” so the engine decides “how.”
Installation and first contact
Requirements and installation: uv first, pip as fallback
Polars 2.x requires Python 3.11 or higher. I recommend installing with uv: it is a package manager written in Rust, resolves dependencies much faster than pip, and caches downloads across projects. The difference is especially noticeable when you install extras or recreate the environment several times.
# Install uv (macOS/Linux)
curl -LsSf https://astral.sh/uv/install.sh | sh
# In a new project
uv init my-project
cd my-project
uv add polars
# In an existing environment
uv pip install polars
uv add writes the dependency to pyproject.toml, creates .venv/ if it does not exist, and pins the version in uv.lock. uv pip install is the direct pip equivalent, but using uv’s resolver and cache.
For optional features, extras are installed the same way:
# Interoperability
uv add "polars[pandas,numpy,pyarrow]"
# Excel reading
uv add "polars[excel]"
# Databases
uv add "polars[database]"
# Cloud storage
uv add "polars[fsspec]"
# GPU (NVIDIA)
uv add "polars[gpu]"
# Everything
uv add "polars[all]"
If you do not have uv or need a one-off global install, pip is still perfectly valid:
pip install polars
pip install "polars[all]"
The speed difference does not come from compiling Polars (the wheels are already compiled), but from dependency resolution, parallel downloads, and caching. In a project with many dependencies, uv can take seconds where pip takes minutes.
If your CPU is older and does not support AVX2:
uv add "polars[rtcompat]"
# or: pip install "polars[rtcompat]"
If you expect more than 4.3 billion rows (2^32), install the 64-bit index:
uv add "polars[rt64]"
# or: pip install "polars[rt64]"
Your first DataFrame
import polars as pl
from datetime import date
df = pl.DataFrame(
{
"name": ["Alice Archer", "Ben Brown", "Chloe Cooper", "Daniel Donovan"],
"birthdate": [
date(1997, 1, 10),
date(1985, 2, 15),
date(1983, 3, 22),
date(1981, 4, 30),
],
"weight": [57.9, 72.5, 53.6, 83.1],
"height": [1.56, 1.77, 1.65, 1.75],
}
)
print(df)
Expected output:
shape: (4, 4)
┌────────────────┬────────────┬────────┬────────┐
│ name ┆ birthdate ┆ weight ┆ height │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ date ┆ f64 ┆ f64 │
╞════════════════╪════════════╪════════╪════════╡
│ Alice Archer ┆ 1997-01-10 ┆ 57.9 ┆ 1.56 │
│ Ben Brown ┆ 1985-02-15 ┆ 72.5 ┆ 1.77 │
│ Chloe Cooper ┆ 1983-03-22 ┆ 53.6 ┆ 1.65 │
│ Daniel Donovan ┆ 1981-04-30 ┆ 83.1 ┆ 1.75 │
└────────────────┴────────────┴────────┴────────┘
Look at the header: shape, column name, data type, and values. Polars tells you the type of each column, something pandas does not do by default.
Inspect without loading everything
print(df.head(3)) # first rows
print(df.tail(3)) # last rows
print(df.sample(2)) # random rows
print(df.glimpse()) # per-column summary (Python only)
print(df.describe()) # statistics
print(df.schema) # data types
glimpse is especially useful for wide DataFrames: it prints one line per column instead of a giant table.
Write and read
df.write_csv("output.csv")
df.write_parquet("output.parquet")
df_csv = pl.read_csv("output.csv", try_parse_dates=True)
df_parquet = pl.read_parquet("output.parquet")
For large files, use scan_* instead of read_*:
lf = pl.scan_parquet("output.parquet")
A LazyFrame loads nothing yet. It is a promise of a query. We return to this in the lazy API section.
The mental model: Series, DataFrame, LazyFrame
Series
A Series is a column: a one-dimensional homogeneous structure with a name and a data type.
s = pl.Series("ints", [1, 2, 3, 4, 5])
print(s)
shape: (5,)
Series: 'ints' [i64]
[
1
2
3
4
5
]
You can force the type:
s = pl.Series("uints", [1, 2, 3], dtype=pl.UInt64)
DataFrame
A DataFrame is a collection of Series with the same number of rows, each with a name and type. It is two-dimensional and heterogeneous: each column can have a different type.
df = pl.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]})
print(df.schema)
Schema({'a': Int64, 'b': String})
LazyFrame
A LazyFrame is the representation of a query that has not run yet. It has no materialized data; it has a plan. When you call .collect(), the optimizer rewrites the plan and the engine executes it.
lf = pl.scan_parquet("sales.parquet")
result = (
lf.filter(pl.col("amount") > 100)
.group_by("category")
.agg(pl.col("amount").sum())
.collect()
)
The difference between DataFrame and LazyFrame is the difference between “having the data” and “knowing how to get it.” The lazy API is the key to performance.
Data types
Polars supports:
- Numeric:
Int8/16/32/64/128,UInt8/16/32/64/128,Float16/32/64,Decimal. - Temporal:
Date,Time,Datetime,Duration. - Text:
String,Categorical,Enum. - Nested:
List,Array,Struct,Map. - Other:
Boolean,Binary,Object,Null.
The golden rule: choose the smallest type that can hold your data. A UInt8 for ages (0-255) takes 1 byte; an Int64 takes 8. Across 100 million rows, the difference is 700 MB.
df = pl.DataFrame(
{"name": ["Alice", "Ben"], "age": [27, 39]},
schema_overrides={"age": pl.UInt8},
)
print(df.schema)
Schema({'name': String, 'age': UInt8})
Null vs NaN
In Polars, null is a missing value and NaN is an undefined floating-point number. They are not the same. pl.col("x").is_null() detects missing values; pl.col("x").is_nan() detects NaN. Confusing them is a classic source of aggregation bugs.
df = pl.DataFrame({"x": [1.0, None, float("nan")]})
print(df.select(
pl.col("x").is_null().alias("is_null"),
pl.col("x").is_nan().alias("is_nan"),
))
Expressions and contexts: the heart of Polars
If you learn only one thing from this guide, let it be this: Polars is written with expressions inside contexts.
What is an expression
An expression is a lazy transformation. It does not run until it is given a context.
bmi_expr = pl.col("weight") / (pl.col("height") ** 2)
print(bmi_expr)
[(col("weight")) / (col("height").pow([dyn int: 2]))]
The expression does nothing on its own. It is a recipe. Contexts are the kitchens where it runs.
The four fundamental contexts
select
Selects and transforms columns. Each expression produces one column in the result.
result = df.select(
pl.col("name"),
pl.col("birthdate").dt.year().alias("birth_year"),
(pl.col("weight") / (pl.col("height") ** 2)).alias("bmi"),
)
print(result)
Output:
shape: (4, 3)
┌────────────────┬────────────┬───────────┐
│ name ┆ birth_year ┆ bmi │
│ --- ┆ --- ┆ --- │
│ str ┆ i32 ┆ f64 │
╞════════════════╪════════════╪═══════════╡
│ Alice Archer ┆ 1997 ┆ 23.791913 │
│ Ben Brown ┆ 1985 ┆ 23.141498 │
│ Chloe Cooper ┆ 1983 ┆ 19.687787 │
│ Daniel Donovan ┆ 1981 ┆ 27.134694 │
└────────────────┴────────────┴───────────┘
with_columns
Like select, but keeps all original columns and adds the new ones.
result = df.with_columns(
birth_year=pl.col("birthdate").dt.year(),
bmi=pl.col("weight") / (pl.col("height") ** 2),
)
print(result)
Output: the four original columns plus birth_year and bmi. It is the context you will use most to enrich data.
filter
Filters rows with a boolean expression.
result = df.filter(
pl.col("birthdate").is_between(date(1982, 12, 31), date(1996, 1, 1)),
pl.col("height") > 1.7,
)
print(result)
Output: only Ben Brown. You can pass multiple predicates as separate arguments; Polars combines them with AND. It is more readable than chaining &.
group_by + agg
Groups rows by one or more expressions and applies aggregations to each group.
result = df.group_by(
(pl.col("birthdate").dt.year() // 10 * 10).alias("decade"),
maintain_order=True,
).agg(
pl.len().alias("sample_size"),
pl.col("weight").mean().round(2).alias("avg_weight"),
pl.col("height").max().alias("tallest"),
)
print(result)
Output:
shape: (2, 4)
┌────────┬─────────────┬────────────┬─────────┐
│ decade ┆ sample_size ┆ avg_weight ┆ tallest │
│ --- ┆ --- ┆ --- ┆ --- │
│ i32 ┆ u32 ┆ f64 ┆ f64 │
╞════════╪═════════════╪════════════╪═════════╡
│ 1990 ┆ 1 ┆ 57.9 ┆ 1.56 │
│ 1980 ┆ 3 ┆ 69.73 ┆ 1.77 │
└────────┴─────────────┴────────────┴─────────┘
maintain_order=True preserves the order in which groups appear. It is slower, but useful for reproducible results.
Expression expansion
An expression can apply to several columns at once. Polars calls this expression expansion:
result = df.select(
pl.col("name"),
(pl.col("weight", "height") * 0.95).round(2).name.suffix("-5%"),
)
print(result)
Output:
shape: (4, 3)
┌────────────────┬───────────┬───────────┐
│ name ┆ weight-5% ┆ height-5% │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞════════════════╪═══════════╪═══════════╡
│ Alice Archer ┆ 55.0 ┆ 1.48 │
│ Ben Brown ┆ 68.88 ┆ 1.68 │
│ Chloe Cooper ┆ 50.92 ┆ 1.57 │
│ Daniel Donovan ┆ 78.94 ┆ 1.66 │
└────────────────┴───────────┴───────────┘
You can also select by data type:
# All Float64 columns, multiplied by 1.1
expr = (pl.col(pl.Float64) * 1.1).name.suffix("*1.1")
result = df.select(expr)
This is especially useful in wide DataFrames: you do not need to list 50 columns.
Alias and names
.alias("new_name")renames an expression..name.suffix("_x"),.name.prefix("avg_"),.name.keep()manipulate names.- Named expressions (
bmi=...) work inselect,with_columns, andagg.
df.select(
pl.col("weight").mean().alias("avg_weight"),
pl.col("height").max().name.prefix("max_"),
)
Lazy API and optimizations: where performance lives
The lazy API is not a variant of the eager API. It is the API for production. The difference is when work happens.
Eager vs lazy
Eager: every operation runs immediately and produces an intermediate result.
df = pl.read_csv("iris.csv")
df_small = df.filter(pl.col("sepal_length") > 5)
df_agg = df_small.group_by("species").agg(pl.col("sepal_width").mean())
Lazy: you build the complete plan and execute it once.
q = (
pl.scan_csv("iris.csv")
.filter(pl.col("sepal_length") > 5)
.group_by("species")
.agg(pl.col("sepal_width").mean())
)
df = q.collect()
The second version can read only the necessary rows and columns, and run the aggregation in parallel. The first reads everything, filters, then aggregates.
scan_* vs read_*
read_csv,read_parquet,read_json: load everything into memory and return aDataFrame.scan_csv,scan_parquet,scan_json: return aLazyFrame, load nothing, and enable pushdown.
Rule: if the data will go through more than two transformations, use scan_*.
explain: see the plan
print(q.explain())
Simplified output:
AGGREGATE[maintain_order: false]
[col("sepal_width").mean()] BY [col("species")]
FROM
simple π 2/2 ["species", "sepal_width"]
Csv SCAN [iris.csv]
PROJECT 3/5 COLUMNS
SELECTION: col("sepal_length") > 5.0
ESTIMATED ROWS: 167
Two things happened without you asking:
- Predicate pushdown: the filter was applied during reading, not after.
- Projection pushdown: only 3 of 5 columns were read.
That is the optimizer at work.
The optimizations Polars does for you
| Optimization | What it does |
|---|---|
| Predicate pushdown | Applies filters as early as possible, even at scan |
| Projection pushdown | Reads only necessary columns |
| Slice pushdown | Loads only the necessary slice (head, tail) |
| Common subplan elimination | Caches repeated subplans |
| Simplify expressions | Constant folding and replacing with cheaper operations |
| Join ordering | Orders joins to reduce memory |
| Type coercion | Converts types so operations are valid and efficient |
| Cardinality estimation | Estimates cardinality to choose the group_by strategy |
You do not need to enable anything. You just need to write lazy and avoid breaking the plan with imperative operations.
Streaming
For datasets that do not fit in RAM:
df = q.collect(engine="streaming")
The streaming engine processes in batches and can spill to disk if it runs out of memory. Not every operation is streaming; some fall back to the in-memory engine. To inspect the physical plan:
q.show_graph(plan_stage="physical", engine="streaming")
When to use eager
- Interactive exploration where you want to see intermediate results.
- Small DataFrames (< 100 MB).
- When you need to inspect the schema before continuing.
For everything else, lazy.
IO: read and write without pain
Polars supports CSV, Parquet, JSON, NDJSON, Excel, Avro, IPC/Arrow, Delta Lake, Iceberg, databases, and cloud storage.
Parquet: the default format
Parquet is columnar, compressed, and typed. It is 5-10x smaller than CSV and reads 10-50x faster. If you will process a dataset more than once, convert it to Parquet.
# Convert once
df = pl.read_csv("sales.csv")
df.write_parquet("sales.parquet")
# Read later
df = pl.read_parquet("sales.parquet")
# Lazy (recommended)
lf = pl.scan_parquet("sales.parquet")
You can read only some columns:
df = pl.read_parquet("sales.parquet", columns=["date", "amount", "category"])
And in lazy mode, projection pushdown does it automatically.
CSV
df = pl.read_csv(
"sales.csv",
try_parse_dates=True,
infer_schema_length=10_000,
null_values=["", "NA", "NULL"],
)
For large files, use scan_csv:
lf = pl.scan_csv("sales.csv", try_parse_dates=True)
JSON and NDJSON
df = pl.read_json("data.json")
lf = pl.scan_ndjson("events.ndjson")
Excel
# Requires the Excel extra
df = pl.read_excel("report.xlsx", sheet_name="Sales")
Cloud storage
# Requires the fsspec extra
lf = pl.scan_parquet("s3://bucket/sales/*.parquet")
With scan_parquet on cloud, Polars applies predicate and projection pushdown before downloading: it only pulls the necessary columns and rows.
Databases
# Requires the database extra
df = pl.read_database(
"SELECT * FROM sales WHERE date >= '2025-01-01'",
connection="postgresql://user:pass@host/db",
)
Writing results
df.write_parquet("result.parquet", compression="zstd")
df.write_csv("result.csv")
df.write_json("result.json")
For large results, write in streaming:
q.sink_parquet("result.parquet")
sink_parquet runs the query in streaming and writes directly to disk, without materializing everything in memory.
Essential transformations
Select, rename, drop
df.select("name", "weight")
df.select(pl.col("name"), pl.col("weight").alias("weight_kg"))
df.drop("birthdate")
df.rename({"weight": "weight_kg", "height": "height_m"})
Sort
df.sort("weight", descending=True)
df.sort(["height", "weight"], descending=[False, True])
Filter nulls
df.filter(pl.col("weight").is_not_null())
df.drop_nulls(subset=["weight"])
df.fill_null(0)
df.fill_null(strategy="forward")
Unique and duplicates
df.unique(subset=["name"], keep="first")
df.is_duplicated()
df.drop_duplicates()
Casting
df.with_columns(
pl.col("weight").cast(pl.Float32),
pl.col("birthdate").cast(pl.Datetime),
)
Joins
Polars supports the usual joins and some that pandas does not have natively.
# Inner (default)
df.join(df2, on="name", how="inner")
# Left
df.join(df2, on="name", how="left")
# Full
df.join(df2, on="name", how="full", coalesce=True)
# Semi: left rows with a match, without right columns
df.join(df2, on="name", how="semi")
# Anti: left rows WITHOUT a match
df.join(df2, on="name", how="anti")
# Cross: Cartesian product
df.join(df2, how="cross")
# Non-equi: arbitrary predicate
df.join_where(df2, pl.col("cash") > pl.col("cost"))
# Asof: match on nearest key (time series)
trades.join_asof(quotes, on="time", by="stock", strategy="backward")
The asof join is the one you need for financial and telemetry data: for each trade, find the most recent quote at or before the trade time.
Concatenate
pl.concat([df1, df2], how="vertical") # stack rows
pl.concat([df1, df2], how="horizontal") # add columns
pl.concat([df1, df2], how="diagonal") # align columns by name
pl.concat([df1, df2], how="diagonal_relaxed") # align and cast
Pivot and unpivot
# Long to wide
df.pivot(on="category", index="date", values="amount", aggregate_function="sum")
# Wide to long
df.unpivot(on=["january", "february", "march"], index="product", variable_name="month", value_name="sales")
Explode
Turns a list column into rows.
df = pl.DataFrame({"id": [1, 2], "tags": [["a", "b"], ["c"]]})
print(df.explode("tags"))
shape: (3, 2)
┌─────┬──────┐
│ id ┆ tags │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪══════╡
│ 1 ┆ a │
│ 1 ┆ b │
│ 2 ┆ c │
└─────┴──────┘
Missing data
df.select(pl.col("x").is_null().sum().alias("nulls"))
df.with_columns(pl.col("x").fill_null(0))
df.with_columns(pl.col("x").interpolate())
Polars distinguishes null from NaN. For floats, check both.
Aggregations and window functions
Aggregations
df.group_by("category").agg(
pl.len().alias("n"),
pl.col("amount").sum().alias("total"),
pl.col("amount").mean().alias("average"),
pl.col("amount").median().alias("median"),
pl.col("amount").std().alias("std_dev"),
pl.col("amount").min().alias("minimum"),
pl.col("amount").max().alias("maximum"),
pl.col("amount").quantile(0.95).alias("p95"),
)
You can group by expressions, not just columns:
df.group_by(
(pl.col("date").dt.year() // 10 * 10).alias("decade"),
(pl.col("amount") > 1000).alias("large"),
).agg(pl.col("amount").sum())
Window functions
A window function computes an aggregation per group but returns a result the same size as the original DataFrame. It is the difference between group_by (collapses rows) and over (preserves rows).
df = pl.DataFrame({
"athlete": ["A", "B", "C", "D", "E", "F"],
"country": ["PT", "NL", "NL", "PT", "PT", "NL"],
"rank": [6, 1, 5, 4, 2, 3],
})
result = df.with_columns(
pl.col("rank").mean().over("country").alias("country_mean"),
pl.col("rank").rank("dense").over("country").alias("country_rank"),
)
print(result)
over accepts several grouping columns and a mapping_strategy:
"group_to_rows"(default): keeps the original order and maps results back to the group rows."explode": groups results, faster, but reorders."join": aggregates results into lists and repeats them on every row of the group.
df.with_columns(
pl.col("rank").sort().over("country", mapping_strategy="join").alias("country_ranks")
)
Rolling and dynamic group_by
For time series:
df.rolling("date", period="7d", offset="0d", closed="right").agg(
pl.col("amount").sum().alias("sales_7d")
)
And dynamic time-window groupings:
df.group_by_dynamic("date", every="1d", period="7d", closed="right").agg(
pl.col("amount").sum()
)
Advanced types and namespaces
Strings: .str namespace
df.with_columns(
pl.col("name").str.to_lowercase().alias("name_lower"),
pl.col("name").str.split(" ").list.first().alias("first_name"),
pl.col("name").str.contains("Archer").alias("is_archer"),
pl.col("name").str.replace(" ", "_").alias("slug"),
pl.col("name").str.len_chars().alias("len"),
)
Lists and arrays: .list and .arr namespaces
df = pl.DataFrame({"tags": [["a", "b"], ["c"], ["d", "e"]]})
df.with_columns(
pl.col("tags").list.len().alias("n_tags"),
pl.col("tags").list.first().alias("first_tag"),
pl.col("tags").list.contains("b").alias("has_b"),
pl.col("tags").list.join("|").alias("tags_str"),
)
The difference: List is variable length per row; Array is a fixed length known in the schema.
Structs: .struct namespace
df = pl.DataFrame({
"person": [
{"name": "Alice", "age": 27},
{"name": "Ben", "age": 39},
]
})
df.with_columns(
pl.col("person").struct.field("name").alias("name"),
pl.col("person").struct.field("age").alias("age"),
)
Categorical and Enum
Categorical encodes strings into a runtime dictionary. Enum is a predefined, ordered set of categories.
types = ["Grass", "Fire", "Water"]
type_enum = pl.Enum(types)
df = df.with_columns(pl.col("type").cast(type_enum))
Use Enum when categories are known and finite; use Categorical when they are not. Both save memory compared to String.
Folds
For horizontal operations across columns:
df.select(
pl.sum_horizontal(pl.col("january", "february", "march")).alias("quarter")
)
UDFs: when and when not
Polars allows Python functions with map_elements, but every call crosses the Rust-Python boundary and loses parallelism. Use them only when no native expression exists.
# Avoid this if you can use an expression
df.with_columns(
pl.col("name").map_elements(lambda x: x.upper(), return_dtype=pl.String)
)
# Better: native expression
df.with_columns(pl.col("name").str.to_uppercase())
Performance: recipes and anti-patterns
Rule 1: write lazy
# Bad
df = pl.read_parquet("data.parquet")
result = df.filter(...).group_by(...).agg(...)
# Good
result = (
pl.scan_parquet("data.parquet")
.filter(...)
.group_by(...)
.agg(...)
.collect()
)
Rule 2: filter and select before joining
# Bad: join two full tables
df1.join(df2, on="id")
# Good: reduce first
df1.filter(pl.col("date") >= "2025-01-01").join(
df2.select("id", "category"), on="id"
)
Rule 3: use Parquet, not CSV
pl.scan_parquet("data.parquet") # columnar, compressed, fast
Rule 4: avoid map_elements in loops
Every row that crosses into Python costs microseconds. Across 10 million rows, that is minutes. If the operation exists as an expression, use it.
Rule 5: measure before optimizing
import time
start = time.perf_counter()
result = q.collect()
print(f"{(time.perf_counter() - start):.2f}s")
And use explain() to check the plan is what you expect.
Rule 6: streaming for data that does not fit
q.collect(engine="streaming")
Rule 7: small types
pl.col("age").cast(pl.UInt8)
pl.col("category").cast(pl.Categorical)
Anti-patterns
- Converting to pandas for intermediate operations. Breaks the plan and loses the engine.
- Using
apply/map_elementsfor everything. It is the equivalent of writing pandas in Polars. - Calling
collect()inside a loop. Each collect materializes and restarts the plan. - Not filtering before large joins. Joins multiply memory.
- Ignoring the schema. An
Int64for everything doubles memory unnecessarily. - Using
read_*whenscan_*was enough. - Not measuring. Performance intuition is usually wrong.
SQL, interop, and ecosystem
SQL
Polars translates SQL into expressions and runs it with its own engine. There is no separate SQL engine.
import polars as pl
df = pl.DataFrame({"a": [1, 2, 3]})
with pl.SQLContext(df=df, eager=True) as ctx:
result = ctx.execute("SELECT a * 2 AS double FROM df WHERE a > 1")
print(result)
You can mix SQL and expressions:
result = (
pl.sql("SELECT * FROM df WHERE a > 1")
.with_columns(double=pl.col("a") * 2)
.collect()
)
Interop with pandas, NumPy, and PyArrow
# pandas -> Polars
df = pl.from_pandas(pd_df)
# Polars -> pandas
pdf = df.to_pandas()
# NumPy
arr = df.to_numpy()
df = pl.from_numpy(arr, schema=["a", "b"])
# PyArrow
table = df.to_arrow()
df = pl.from_arrow(table)
Conversion from pandas with the Arrow backend is nearly zero-copy. From NumPy it can be expensive.
GPU
uv add "polars[gpu]"
result = q.collect(engine="gpu")
Requires a compatible NVIDIA GPU and cudf-polars. Not every operation is supported.
Plugins and ecosystem
Polars supports expression and IO plugins written in Rust. There is also Polars Cloud/Nanook for horizontal scaling on a cluster. For most teams, the local engine with streaming is enough.
Guided project: sales analysis from zero to result
Let’s walk through a complete case with a sales dataset. Suppose a 10 GB Parquet with columns: date, customer_id, product, category, quantity, unit_price, region.
Step 1: inspect without loading
import polars as pl
lf = pl.scan_parquet("sales.parquet")
print(lf.schema)
print(lf.head(5).collect())
print(lf.select(pl.len()).collect())
Step 2: clean and enrich
clean = (
lf.filter(pl.col("quantity") > 0)
.with_columns(
(pl.col("quantity") * pl.col("unit_price")).alias("amount"),
pl.col("date").cast(pl.Date),
pl.col("region").cast(pl.Categorical),
)
.filter(pl.col("amount").is_not_null())
)
Step 3: aggregate by month and category
monthly = (
clean.with_columns(pl.col("date").dt.truncate("1mo").alias("month"))
.group_by("month", "category")
.agg(
pl.col("amount").sum().alias("sales"),
pl.col("quantity").sum().alias("units"),
pl.len().alias("transactions"),
pl.col("customer_id").n_unique().alias("unique_customers"),
)
.sort("month", "category")
)
Step 4: window function for share
with_share = monthly.with_columns(
(pl.col("sales") / pl.col("sales").sum().over("month")).alias("month_share"),
pl.col("sales").rank("dense", descending=True).over("month").alias("month_rank"),
)
Step 5: join with product catalog
catalog = pl.scan_parquet("catalog.parquet").select(
"product", "margin", "supplier"
)
enriched = clean.join(catalog, on="product", how="left")
Step 6: top customers by region
top_customers = (
enriched.group_by("region", "customer_id")
.agg(pl.col("amount").sum().alias("customer_total"))
.with_columns(
pl.col("customer_total")
.rank("dense", descending=True)
.over("region")
.alias("region_rank")
)
.filter(pl.col("region_rank") <= 10)
.sort("region", "region_rank")
)
Step 7: write in streaming
(
with_share
.sink_parquet("monthly_result.parquet")
)
Step 8: verify
result = pl.read_parquet("monthly_result.parquet")
print(result.head(10))
print(result.schema)
print(result.shape)
This flow reads only the necessary columns, filters early, joins after reducing, uses window functions instead of subqueries, and writes in streaming. It is the pattern that scales from a laptop to a server.
Checklists and learning path
Beginner
- Install Polars and create DataFrames from dictionaries, CSV, and Parquet.
- Understand Series, DataFrame, and LazyFrame.
- Use
select,with_columns,filter, andgroup_by. - Read and write CSV and Parquet.
- Inspect with
head,tail,glimpse,describe,schema.
Intermediate
- Write lazy queries with
scan_*andcollect. - Read
explain()and understand predicate/projection pushdown. - Do every join type, including
join_asof. - Use window functions with
over. - Handle
nullvsNaN. - Use
str,list,struct, andEnum.
Expert
- Optimize queries by measuring time and memory.
- Use streaming for datasets that do not fit in RAM.
- Avoid UDFs and row-wise operations.
- Design schemas with small types and categoricals.
- Use SQLContext or
pl.sqlwhen the team already knows SQL. - Interoperate with pandas/Arrow without unnecessary copies.
- Evaluate GPU or Nanook only when the case justifies it.
Polars does not make you a better analyst. It removes the excuse that “the data was too big.” When the tool stops being the bottleneck, the bottleneck is you: the questions you ask and the data model you design. That is where the real work begins.
Related articles
By relevance
Excel with Polars: read, explore, and query huge sheets without dying in the attempt
Practical guide to Excel with Polars: read sheets, inspect columns, paginate, search, sort, filter, and speed everything up with calamine and Parquet.
Large data analysis with Python: from pandas to Polars and DuckDB
How to analyze datasets that don't fit in memory with Python: Polars, DuckDB, chunking, and strategies that avoid OOM.
Full Stack Go: Notes and Todos App with HTMX, Templ and SQLite
Build a complete Notes and Todos app in Go: markdown notes with tags, todo checklists, full-text search, auth, HTMX reactivity, Templ templates, and SQLite.
Go 1.25 Medical API: DDD, TDD, BDD, PostgreSQL, Redis — Complete Clinical System
Build a production-ready medical records API in Go 1.25 with DDD, TDD, BDD, Gherkin scenarios, PostgreSQL, Redis. Full patient history, clinical boards, and every file explained.