Start with the pandas transformation your application spends the most time on. Port the filter, join and aggregation, then compare the resulting rows by key. Column names, null handling and output order can differ even when a small example looks right.
Why Polars Is Different at a Fundamental Level
Pandas works with labeled columns and indexes. Polars uses expressions and offers a lazy query optimizer that can push eligible projections and filters to the reader. Parallelism and memory reuse depend on the operation, layout and data source. Polars guide for pandas users
The Benchmark Numbers
Polars published a PDS-H comparison in June 2025. At scale factor 10, aggregating the benchmark suite’s timings gave 3.89 seconds for Polars 1.30.0 streaming, 5.87 seconds for DuckDB 1.3.0 and 365.71 seconds for pandas 2.2.3. The machine had 96 vCPUs and 192 GB of RAM. The pandas run enabled Copy-on-Write and Arrow dtypes. These are the upstream authors’ timings. PDS-H methods, versions and results
At scale factor 100 the authors reported 23.94 seconds for Polars streaming and 19.65 seconds for DuckDB. They did not publish a pandas time at this scale. Your query may use a different join, data layout or output type. For a small benchmark with identical expected totals and raw repeated timings, use our three-engine fixture.
Core API Differences
The biggest adjustment when switching from Pandas is the expression-based API. In Pandas, you often manipulate DataFrames directly. In Polars, you write expressions that describe transformations, and the engine applies them.
Reading Data
import pandas as pd
import polars as pl
# Pandas
df = pd.read_csv("data.csv")
df = pd.read_parquet("data.parquet")
# Polars (eager — runs immediately)
df = pl.read_csv("data.csv")
df = pl.read_parquet("data.parquet")
# Polars (lazy — recommended for large files)
lf = pl.scan_parquet("data.parquet")
lf = pl.scan_csv("data.csv")
The scan_* functions don’t read the file yet. They build a query plan. More on that in the lazy evaluation section.
Filtering Rows
# Pandas
result = df[df["amount"] > 100]
# Polars
result = df.filter(pl.col("amount") > 100)
GroupBy and Aggregation
# Pandas
result = (
df.groupby("category")
.agg({"sales": "sum", "units": "mean"})
.reset_index()
.sort_values("sales", ascending=False)
)
# Polars
result = (
df.group_by("category")
.agg([
pl.col("sales").sum(),
pl.col("units").mean()
])
.sort("sales", descending=True)
)
Notice there’s no reset_index() in Polars. Polars has no row index — one of the bigger conceptual shifts. You never need to reset it because it doesn’t exist.
Adding and Transforming Columns
This is where Polars really shines. In Pandas, adding multiple columns often means multiple passes over the data. In Polars, with_columns runs all transformations in parallel in a single pass:
# Pandas (three separate operations, three passes)
df["revenue_usd"] = df["revenue"] * 1.1
df["name_upper"] = df["name"].str.upper()
df["is_large"] = df["revenue"] > 10000
# Polars (one call, all columns computed in parallel)
df = df.with_columns([
(pl.col("revenue") * 1.1).alias("revenue_usd"),
pl.col("name").str.to_uppercase().alias("name_upper"),
(pl.col("revenue") > 10000).alias("is_large")
])
Conditional Logic
Pandas uses .loc[] for conditional assignment. Polars uses when/then/otherwise:
# Pandas
df.loc[df["value"] > 100, "category"] = "high"
# Polars
df = df.with_columns(
pl.when(pl.col("value") > 100)
.then(pl.lit("high"))
.otherwise(pl.col("category"))
.alias("category")
)
Joins
# Pandas
result = df1.merge(df2, on="id", how="inner")
# Polars
result = df1.join(df2, on="id", how="inner")
One important difference: Polars joins don’t preserve row insertion order. If order matters, add an explicit .sort() after the join.
Schema Strictness
Polars is strict about types. Pandas will silently coerce mismatched types; Polars raises an error:
# Pandas: silently converts int to float
df1 = pd.DataFrame({"a": [1, 2], "b": [3.0, 4.0]})
df2 = pd.DataFrame({"a": [5, 6], "b": [7, 8]}) # b is int
result = pd.concat([df1, df2]) # works, b becomes float64
# Polars: raises SchemaError
df1 = pl.DataFrame({"a": [1, 2], "b": [3.0, 4.0]})
df2 = pl.DataFrame({"a": [5, 6], "b": [7, 8]})
pl.concat([df1, df2]) # SchemaError: column 'b' has dtype i64 but expected f64
This strictness catches bugs early. But it means migration requires explicit .cast() calls in places where Pandas was silently handling type mismatches.
Lazy Evaluation: The Feature That Changes Everything
If you only learn one Polars concept, make it lazy evaluation. It’s what separates Polars from “fast Pandas” and makes it a genuine query engine.
How It Works
When you call pl.scan_parquet() or df.lazy(), Polars doesn’t execute anything. It builds a query plan — a description of what you want to compute. Only when you call .collect() does it actually run.
result = (
pl.scan_parquet("clickstream.parquet") # no data read yet
.filter(pl.col("click_velocity") > 10) # adds filter to plan
.group_by("user_id") # adds aggregation to plan
.agg(pl.col("amount").sum())
.sort("amount", descending=True)
.collect() # NOW it executes
)
Between scan_parquet and collect, Polars’ query optimizer rewrites your plan to be as efficient as possible.
What the Optimizer Does Automatically
A filter can reach the file reader when the plan permits it. Parquet row-group statistics may then skip whole row groups. The fraction of matching rows does not directly determine bytes read.
Projection pushdown: If your query only uses 3 columns from a 100-column Parquet file, Polars only reads those 3 columns. Parquet’s columnar format makes this essentially free.
Common subexpression elimination: If you reference the same expression twice, Polars computes it once.
Join reordering: Polars automatically picks the most efficient join order based on estimated cardinalities.
Inspecting the Query Plan
lf = (
pl.scan_parquet("transactions.parquet")
.filter(pl.col("amount") > 100)
.group_by("user_id")
.agg(pl.col("amount").sum())
)
# See what the optimizer produces
print(lf.explain(optimized=True))
This is useful for debugging performance issues — you can verify that predicate pushdown is actually happening.
Streaming: Processing Data Larger Than RAM
With Polars 2.0, lazy collection on CPU uses the streaming engine by default. lf.collect() still returns the entire result to memory. To write an output that would be too large to materialize, use a lazy sink such as lf.sink_parquet("output.parquet") and measure peak memory and temporary disk use on your plan. Our 2.0 CPU example checks a small result and dates the engine change.
When Lazy Doesn’t Work
A lazy query needs a schema. For a pivot where the possible output column names are known, Polars 2.0.0 can plan the pivot using on_columns. The example fixes the two expected regions. When names are data-dependent, decide on the allowed categories first or materialize at that boundary. LazyFrame pivot reference
import polars as pl
sales = pl.LazyFrame({"store": ["s", "s"], "region": ["east", "west"], "units": [2, 3]})
wide = sales.pivot(on="region", on_columns=["east", "west"], index="store", values="units")
assert wide.collect().rows() == [("s", 2, 3)]
Migrating from Pandas: A Practical Approach
Don’t rewrite everything at once. Profile first, then migrate the bottlenecks.
Step 1: Find Your Bottlenecks
import cProfile
cProfile.run("run_pipeline()", sort="cumulative")
Or use py-spy for a lower-overhead sampling profiler on running processes. You’re looking for the stages that consume the most time — usually large joins, GroupBy operations on millions of rows, or reading big files.
Step 2: Migrate the Slow Parts First
A real example from a production ETL pipeline: a 5-stage pipeline had one stage doing a join on two 10M-row tables. That stage took 40 minutes in Pandas. After migrating just that stage to Polars, it dropped to 4 minutes. The other four stages stayed in Pandas.
Step 3: Handle the Boundaries
Polars and Pandas interoperate cleanly:
# Polars → Pandas (for scikit-learn, seaborn, etc.)
df_pandas = df_polars.to_pandas()
# Pandas → Polars
df_polars = pl.from_pandas(df_pandas)
# Polars → NumPy (lower overhead than going through Pandas)
X = df_polars.select(["feature1", "feature2"]).to_numpy()
Keep .to_pandas() calls at the boundaries of your pipeline, not scattered throughout. Some conversions can reuse Arrow buffers. Measure the target dtype and any copy required by the next operation.
Common Pattern Translations
Replace .apply() with expressions:
# Pandas (slow — single-threaded Python loop)
df["result"] = df["col"].apply(lambda x: x * 2 if x > 0 else 0)
# Polars (fast — vectorized, parallel)
df = df.with_columns(
pl.when(pl.col("col") > 0)
.then(pl.col("col") * 2)
.otherwise(0)
.alias("result")
)
Replace .loc[] indexing:
# Pandas
subset = df.loc[df["status"] == "active", ["id", "name"]]
# Polars
subset = df.filter(pl.col("status") == "active").select(["id", "name"])
No more reset_index():
# Pandas (needed after groupby)
result = df.groupby("col").sum().reset_index()
# Polars (no index, no reset needed)
result = df.group_by("col").agg(pl.all().sum())
When to Use Polars vs Pandas
The honest answer: it depends on your data size and your existing codebase.
Use Polars when:
- A lazy scan can select a small subset of the input columns or row groups
- A representative run fits the memory and temporary-disk budget
- You have join-heavy workloads and a representative join showed a measurable gain
- You’re reading Parquet files (predicate/projection pushdown is a huge win)
- You’re building a new data pipeline from scratch
- You’re in a memory-constrained environment
Stick with Pandas when:
- The existing job meets its latency and memory budget
- You need deep scikit-learn, statsmodels, or seaborn integration
- You’re processing Excel files (Pandas’
read_excelecosystem is mature) - You need HDF5, Stata, SAS, or SPSS formats
- Your team has a large existing Pandas codebase and the migration cost outweighs the benefit
- Your application depends on pandas string or index semantics that a migration would need to reproduce
A pipeline with a NumPy consumer
import polars as pl
import duckdb
# DuckDB for initial SQL-style filtering and aggregation
conn = duckdb.connect(":memory:")
df = conn.query("""
SELECT customer_id, SUM(amount) AS total, COUNT(*) AS txn_count
FROM read_csv('transactions.csv', AUTO_DETECT=TRUE)
WHERE region = 'East'
GROUP BY customer_id
HAVING txn_count > 5
""").pl() # transfer the query result to Polars
# Polars for complex transformations
df = (
df.with_columns(
(pl.col("total") / pl.col("txn_count")).alias("avg_value")
)
.filter(pl.col("avg_value") > 100)
.sort("total", descending=True)
)
# Convert to Pandas/NumPy only at the ML boundary
X = df.select(["total", "txn_count", "avg_value"]).to_numpy()
DuckDB handles SQL-style queries with a familiar interface. Polars handles expression-based transformations. Pandas/NumPy handles the ML framework boundary. Each tool does what it’s best at.
Pitfalls to Watch Out For
Lazy re-scanning: Calling .collect() multiple times on the same scan_parquet re-reads the file each time. Cache intermediate results:
# Bad: reads the file twice
lf = pl.scan_parquet("big_file.parquet")
count = lf.select(pl.len()).collect()
result = lf.filter(...).collect()
# Good: read once, cache
df = pl.read_parquet("big_file.parquet")
count = len(df)
result = df.filter(...)
Join order isn’t preserved: Always add .sort() explicitly if row order matters after a join.
Type casting on migration: Polars won’t silently coerce types. Budget time for explicit .cast() calls when migrating existing Pandas code.
Streaming limitations: Not all operations work in streaming mode. If you get an error, check the Polars docs for streaming-compatible operations.
.to_pandas() cost: Some conversions can reuse Arrow buffers. Measure the target dtype and any copy required by the next operation. Keep conversions at pipeline boundaries, not inside loops.
The Ecosystem Today
Polars has reached the point where most of the Python data stack works with it directly:
- DuckDB: Zero-copy interop via Apache Arrow.
duckdb.sql("SELECT ...").pl()returns a Polars DataFrame. - Plotly: Native Polars support.
- Streamlit:
st.dataframe(polars_df)works directly. - Altair: Native support via Narwhals.
- Pandera: Schema validation for Polars DataFrames.
- Microsoft Fabric: Polars is now in the default Python Notebook build.
Check the consumer’s documented inputs for its installed version. If it accepts a NumPy array, .to_numpy() is one option. Test dtype, null handling, column order and conversion cost at that boundary.
Getting Started
Install Polars:
pip install polars
For Arrow-based extras (recommended):
pip install "polars[pyarrow]"
The official Polars documentation is genuinely good — the migration guide from Pandas is worth reading if you’re doing a serious migration.
The Bottom Line
Port the stage that exceeds its time or memory budget. Compare output keys, nulls, totals and order first. Then measure the runtime and peak memory of that stage plus any conversion at the boundary. The PDS-H results show what a particular analytical workload achieved. The decision to migrate belongs to your workload.
Correction, November 25, 2026. This revision attributes the PDS-H measurements to their original setup and removes unrelated speed and memory multipliers. The streaming guidance now identifies the library version.
Your notes on this article
Your name or initials, note and date stay in this browser profile. Anyone using the profile can read them. Delete a note below or clear this site’s browser data. To reach the editors, report a correction.
No notes saved here