If a pandas report already finishes inside its memory and time budget, moving it to another engine adds a maintenance cost. A query that reads a few columns from many files, or a team that needs persistent SQL tables, presents a different choice. Here are three tasks you can reproduce before committing to a rewrite.
The Benchmark That Matters
We ran this fixture with Python 3.12.15, pandas 3.0.1, Polars 2.0.0 and DuckDB 1.2.1. The script sums integer cents for 37 stores, then compares every store’s result. All three engines receive the same 200,000 rows in memory. The timed section includes grouping and converting the 37 output rows to a Python dictionary. It excludes data construction, imports and connection setup. DuckDB scans the registered pandas input, while Polars and pandas start with their own native frames.
import platform
from statistics import median
from timeit import repeat
import duckdb
import pandas as pd
import polars as pl
rows = 200_000
data = {"store": [i % 37 for i in range(rows)],
"cents": [(i * 31) % 10007 for i in range(rows)]}
pdf = pd.DataFrame(data)
pldf = pl.DataFrame(data)
con = duckdb.connect()
con.register("sales", pdf)
def pandas_totals():
return pdf.groupby("store")["cents"].sum().to_dict()
def polars_totals():
return dict(pldf.group_by("store").agg(pl.col("cents").sum()).iter_rows())
def duckdb_totals():
return dict(con.execute("SELECT store, sum(cents) FROM sales GROUP BY store").fetchall())
try:
assert pandas_totals() == polars_totals() == duckdb_totals()
print(platform.platform(), platform.machine(), platform.python_version(),
pd.__version__, pl.__version__, duckdb.__version__)
for query in (pandas_totals, polars_totals, duckdb_totals):
query() # warm this path before measuring
samples = repeat(query, number=1, repeat=7)
print(query.__name__, samples, "median seconds", median(samples))
finally:
con.close()
Record CPU, RAM, thread settings and the raw seven timings alongside the output. For a file-based job, separately time a read from the same file through each engine, record the file size and whether it was already in the OS cache, and compare sorted outputs again. This warm, in-memory example cannot rank cold Parquet scans.
When to Use Pandas
A labeled index, alignment between series, or a library that expects a pandas frame can decide the choice before speed matters. Measure the time and memory at any conversion boundary. For nullable integers and Arrow-backed input, run the CSV backend fixture against the versions you deploy.
When to Use Polars
A lazy plan lets you describe a projection and filter before reading an entire file. Use explain() on the query you actually plan to run. If later code needs rows in date order, include an explicit sort. SQL groups and Polars groups can return the same totals in different orders. Polars lazy query plans
When to Use DuckDB
DuckDB can persist a local database and modify its tables. Try this with a temporary file. The second connection sees the result after the first closes.
from pathlib import Path
from tempfile import TemporaryDirectory
import duckdb
with TemporaryDirectory() as tmp:
path = str(Path(tmp) / "example.duckdb")
with duckdb.connect(path) as db:
db.execute("CREATE TABLE amounts (n INTEGER)")
db.execute("INSERT INTO amounts VALUES (1), (2)")
db.execute("UPDATE amounts SET n = 3 WHERE n = 2")
db.execute("DELETE FROM amounts WHERE n = 1")
with duckdb.connect(path, read_only=True) as db:
assert db.execute("SELECT n FROM amounts").fetchall() == [(3,)]
This covers updates to a persistent table from a local process. Evaluate concurrent writers and transaction throughput separately if the application needs many simultaneous small updates. DuckDB UPDATE · DuckDB concurrency
The Composable Stack
Suppose the forecast runs just before each month begins and the prior month’s books have closed. Start with the customer and month you want to predict. Move each historical observation’s key forward by one calendar month, then join it to those keys. The forecast never needs the current month’s order count or revenue.
from datetime import date
import polars as pl
jan, feb, mar, apr = [date(2026, m, 1) for m in range(1, 5)]
history = pl.DataFrame({"customer": ["A", "A", "B", "A"],
"month": [mar, jan, jan, feb],
"revenue_cents": [300, 100, 50, 200]})
keys = pl.DataFrame({"customer": ["A", "A", "A", "B"],
"month": [jan, feb, mar, mar]})
def make_features(keys, closed_months):
prior = closed_months.select(
"customer", pl.col("month").dt.offset_by("1mo"),
pl.col("revenue_cents").alias("prior_month_cents"),
)
return keys.join(prior, on=["customer", "month"], how="left",
validate="m:1").sort("customer", "month")
features = make_features(keys, history)
assert features["prior_month_cents"].to_list() == [None, 100, 200, None]
assert features.equals(make_features(keys, history.reverse()))
march = keys.filter(pl.col("month") == mar)
known = history.filter(pl.col("month") < mar)
assert make_features(march, known).equals(features.filter(pl.col("month") == mar))
future = pl.DataFrame({"customer": ["A"], "month": [apr]})
assert make_features(future, history)["prior_month_cents"].item() == 300
Customer B has January revenue and no February record, so the March feature is null. Decide whether null means unknown or zero before training. Join actual revenue as a label only after producing features. Keep all customers from a given month on the same side of a time-based train/test cutoff. If the books close late, use records available at the actual cutoff, including their historical revision when figures can be restated. scikit-learn on data leakage
Correction, November 25, 2026. The previous comparison omitted a repeatable timing procedure, understated DuckDB’s write support and used the prediction month’s revenue in a feature. The replacement examples check equivalent answers, persistence and missing calendar months.
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