Sub topic 1
Why and when to migrate from pandas to Polars
Polars is a DataFrame library written in Rust. It reads like pandas on the surface, but it works differently inside. This chapter explains what you gain by moving, what it costs, and how to decide whether a given project should move. Later chapters cover the translation of individual operations.
Prerequisites
This chapter assumes you can do the following:
- Work with pandas DataFrames and Series, including
groupby,merge, and boolean filtering. - Write basic Python, including lambdas and method chaining.
- Recognize common dtypes: integers, floats, strings, and datetimes.
- Install packages with
pip.
To run the example below, install the libraries with pip install polars pandas numpy.
What Polars changes
Four design choices account for most of the differences you will notice.
- Columnar memory in the Arrow format. Each column is stored as one contiguous block. Many operations only touch the columns they need, and the data can be shared with other Arrow-based tools without copying.
- Multi-threaded execution. Polars splits work across CPU cores by default. A plain pandas operation usually runs on one core.
- Expressions. You describe a computation, such as
pl.col("price") * pl.col("qty"), and Polars decides how to run it. Because the engine sees the whole description, it can run independent expressions in parallel. - A lazy engine. With a
LazyFrame, Polars builds a query plan first. It then optimizes the plan before reading any data. For example, it can read only the columns the query uses.
Polars also has no row index. Rows are identified by position only, and there is no set_index, loc, or index alignment. Frames are never modified in place. These two points change how you write code, and the next chapter covers them in depth.
Reasons to migrate
The most common reasons are these:
- Speed on medium and large data. Operations such as group-by, joins, and sorts on millions of rows often run several times faster, because they use all cores and a columnar layout.
- Memory use. Polars generally needs less working memory for a pipeline, and the lazy API can avoid materializing intermediate frames.
- Data larger than comfortable RAM. Lazy queries can run in a streaming mode that processes data in chunks. Check the current documentation for which operations support it.
- Predictable semantics. Missing values are always
null, dtypes are strict, and there is no hidden index alignment. This removes a class of silent bugs, such as an assignment that aligns on index labels and produces unexpectedNaNvalues. - Readable pipelines. One chain of
with_columns,filter, andgroup_bycalls, with noinplaceflags and noreset_index, is easy to review and test.
Recent pandas versions have narrowed some gaps, with optional Arrow-backed dtypes and copy-on-write behavior. Polars still has the stronger query engine, but measure your own workload before assuming a large win.
Reasons not to migrate
Polars is not the better choice everywhere. Weigh these costs:
- Ecosystem integration. Many libraries expect pandas objects, including parts of scikit-learn, statsmodels, and plotting tools. Many now accept Polars frames or can convert them, but you may still need
to_pandas()at boundaries. - Index-centric code. Time series work that relies on a
DatetimeIndex, multi-level indexes, or label alignment has to be redesigned, not just translated. - Small data. On a few thousand rows, both libraries finish in milliseconds. Migrating gains you nothing there.
- Team cost. Expressions take time to learn. A codebase with many contributors and little test coverage is a risky place to start.
- Heavy
applylogic. Row-wise Python functions do not get faster in Polars. They must be rewritten as expressions, which takes effort.
A quick measurement
Do not trust general claims, including the ones above. Time a representative step from your own pipeline. This script compares one pandas pipeline with the equivalent lazy Polars query on synthetic data.
import time
import numpy as np
import pandas as pd
import polars as pl
rng = np.random.default_rng(0)
n = 5_000_000
data = {
"store_id": rng.integers(0, 100, size=n),
"price": rng.random(n) * 100,
"qty": rng.integers(1, 10, size=n),
}
pdf = pd.DataFrame(data)
df = pl.DataFrame(data)
def timed(label, fn):
start = time.perf_counter()
result = fn()
print(f"{label}: {time.perf_counter() - start:.3f}s")
return result
pandas_result = timed(
"pandas",
lambda: (
pdf.assign(total=pdf["price"] * pdf["qty"])
.query("total > 100")
.groupby("store_id")["total"]
.sum()
),
)
polars_result = timed(
"polars",
lambda: (
df.lazy()
.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
.filter(pl.col("total") > 100)
.group_by("store_id")
.agg(pl.col("total").sum())
.collect()
),
)
print(polars_result.sort("store_id").head(3))Timings depend on your hardware, the library versions, and the data. Run the script a few times and ignore the first run, because it includes warm-up costs. A small result is a real result: it tells you the migration will not pay off for that step.
Deciding whether to migrate
The right unit of decision is a pipeline or a service, not the whole company. Work through the questions in this diagram.
Use the table to check the main factors against your situation.
| Factor | Favors Polars | Favors staying on pandas |
|---|---|---|
| Data size | Millions of rows or more | Thousands of rows |
| Workload | Group-by, joins, filters, wide scans | Small exploratory work |
| Code style | Column-wise transformations | Index alignment, row-wise `apply` |
| Dependencies | Mostly your own code | Many pandas-only libraries |
| Team | Willing to learn expressions | Mixed experience, little test coverage |
What the rest of this tutorial covers
The tutorial first covers the mental model: no index, immutable frames, and expressions. It then maps the pandas idioms you use daily to Polars equivalents: reading data, selecting, filtering, creating columns, group-by, window functions, and joins. After that it covers null versus NaN, the lazy API, and replacing apply. The final chapters cover interoperating with pandas, migrating incrementally, and validating that results still match.
Exercise
Your team has a nightly pandas job that processes 200,000 rows and finishes in 4 seconds. A second job joins and aggregates 80 million rows, takes 40 minutes, and often runs out of memory. Which job should you consider migrating first, and what should you do before committing to the migration?
Show answer
Migrate the second job first. It is large, slow, and memory-bound, which are the workloads where Polars' parallel, columnar, lazy engine helps most. The first job takes 4 seconds, so a migration would gain almost nothing. Before committing, time the slow step with a representative sample of real data in both libraries, as in the script above. Also check whether the job depends on index alignment or pandas-only libraries, because those parts would need conversion at the boundaries.