Data analysis · Beginner · 16 min
Choose between pandas, Polars and DuckDB for data analysis
By Padding · Updated 18 Nov 2026
Python 3.15 · pandas 3.1.1 · Polars 2.2.0 · DuckDB 2.0.1 · pyarrow 26.0.1 · NumPy 2.5.5 · uv 0.13 (checked on python:3.15-slim)
You will answer one question, monthly revenue by city from a 2-million-row sales file, in pandas, Polars and DuckDB, time each one, measure its peak memory, prove the three answers match and pass data between them through Arrow.
On this page
pandas, Polars and DuckDB can all read a CSV, group it and sum a column. Articles comparing them tend to pick a winner from someone else's benchmark. A better way to choose is to run your own question through all three on data shaped like yours, and look at three things: how long it takes, how much memory it needs, and how the code reads to you and your team.
This tutorial does that with one question: what was the revenue for each city in each month of 2025? You generate a 2-million-row sales file, answer the question three times, check that the three answers agree to the cent, then pass a result from one library to the others through Apache Arrow, the column format all three understand. At the end you have numbers from your own machine and a short guide to which tool fits which job.
Everything lives in ~/tools-demo, so you can delete it in one go afterwards.
Step 1 · Create a project with all three libraries
Make the project and add the libraries with version ranges that allow patch releases and nothing newer, so a new minor version cannot change behaviour halfway through:
mkdir -p ~/tools-demo/results
cd ~/tools-demo
uv init --no-package --python 3.15
uv add "pandas>=3.1,<3.2" "polars>=2.2,<2.3" "duckdb>=2.0,<2.1" "pyarrow>=26,<27" "numpy>=2.5,<2.6"pyarrow is there for two jobs: writing the sample data, and moving tables between the libraries later. NumPy generates the sample data. pandas would pull it in anyway, but pinning it matters here because NumPy does not promise the same random numbers from a seed across versions.
Check it worked
cd ~/tools-demo
uv run python -c "import pandas, polars, duckdb, pyarrow, numpy; print(pandas.__version__, polars.__version__, duckdb.__version__, pyarrow.__version__, numpy.__version__)"The line reads 3.1.1 2.2.0 2.0.1 26.0.1 2.5.5, or later patch releases of each.
Step 2 · Generate a 2-million-row sales file
Create make_data.py. It builds one year of orders across eight cities with a fixed random seed, so your file has the same rows as anyone else using the same NumPy version, and writes it twice: once as CSV, once as Parquet.
cd ~/tools-demo
cat > make_data.py <<'PY'
import numpy as np
import pyarrow as pa
import pyarrow.csv as pacsv
import pyarrow.parquet as pq
ROWS = 2_000_000
rng = np.random.default_rng(42)
cities = np.array(["Accra", "Addis Ababa", "Cairo", "Dakar", "Johannesburg", "Kigali", "Lagos", "Nairobi"])
days = np.datetime64("2025-01-01") + rng.integers(0, 365, ROWS)
table = pa.table({
"order_id": np.arange(1, ROWS + 1),
"order_date": pa.array(days.astype("datetime64[D]"), type=pa.date32()),
"city": cities[rng.integers(0, len(cities), ROWS)],
"quantity": rng.integers(1, 6, ROWS),
"unit_price": np.round(rng.uniform(2.0, 80.0, ROWS), 2),
})
pacsv.write_csv(table, "sales.csv")
pq.write_table(table, "sales.parquet")
print(f"wrote {table.num_rows:,} rows")
PY
uv run make_data.py
ls -lh sales.csv sales.parquet
head -n 3 sales.csvRevenue for an order is quantity * unit_price. The month comes from order_date.
Check it worked
The script prints wrote 2,000,000 rows. ls shows sales.csv at about 70 MB and sales.parquet at about 15 MB. The first line of the CSV is the header, with each name in double quotes, followed by rows such as 1,2025-02-02,"Johannesburg",2,33.08.
The Parquet file holds the same rows in about a fifth of the space, because it stores each column compressed and keeps the types. If you share data over mobile or prepaid data, as many analysts in Lagos, Nairobi or Accra do, send Parquet rather than CSV.
Step 3 · Answer the question in pandas
Every script in this tutorial reports its peak memory the same way, so put that in a small shared module first. ru_maxrss is the most memory the process held at any point. Linux reports it in kilobytes and macOS in bytes, which the function allows for:
cd ~/tools-demo
cat > peak.py <<'PY'
import resource
import sys
def peak_mb() -> float:
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
# Linux reports kilobytes, macOS reports bytes.
return peak / 1024 / 1024 if sys.platform == "darwin" else peak / 1024
PYpandas works eagerly: each line runs at once and the whole file sits in memory as a DataFrame. Create with_pandas.py:
cd ~/tools-demo
cat > with_pandas.py <<'PY'
import time
import pandas as pd
from peak import peak_mb
start = time.perf_counter()
sales = pd.read_csv("sales.csv", parse_dates=["order_date"])
sales["revenue"] = sales["quantity"] * sales["unit_price"]
sales["month"] = sales["order_date"].dt.to_period("M").dt.start_time
result = (
sales.groupby(["month", "city"], as_index=False)["revenue"]
.sum()
.round({"revenue": 2})
.sort_values(["month", "city"], ignore_index=True)
)
seconds = time.perf_counter() - start
result.to_parquet("results/pandas.parquet", index=False)
print(result.head(3).to_string(index=False))
print(f"pandas rows={len(result)} {seconds:.2f} s peak {peak_mb():.0f} MB")
PY
uv run with_pandas.pyThe timer covers reading the file and computing the answer, not writing it out, and the same goes for the other two scripts.
Check it worked
You see three rows for January 2025 (Accra, Addis Ababa and Cairo, each about 2.6 million) and a last line starting pandas rows=96: 12 months times 8 cities. results/pandas.parquet now exists. Note your time and peak memory.
Step 4 · Answer it in Polars with a lazy query
Polars has an eager API much like pandas, but its strength is the lazy one. scan_csv does not read anything. It starts a query plan, each method adds to the plan, and collect() runs it. Before running, Polars can drop columns the query never uses and run the work across all your CPU cores. Create with_polars.py:
cd ~/tools-demo
cat > with_polars.py <<'PY'
import time
import polars as pl
from peak import peak_mb
start = time.perf_counter()
query = (
pl.scan_csv("sales.csv", try_parse_dates=True)
.with_columns(
revenue=pl.col("quantity") * pl.col("unit_price"),
month=pl.col("order_date").dt.truncate("1mo"),
)
.group_by("month", "city")
.agg(pl.col("revenue").sum().round(2))
.sort("month", "city")
)
result = query.collect()
seconds = time.perf_counter() - start
result.write_parquet("results/polars.parquet")
with pl.Config(float_precision=2, tbl_hide_dataframe_shape=True):
print(result.head(3))
print(f"polars rows={result.height} {seconds:.2f} s peak {peak_mb():.0f} MB")
PY
uv run with_polars.pyEach line is an expression on named columns, with no index to manage. Many people find this easier to read back months later than chained pandas calls.
Check it worked
The table shows the same three January rows with the same revenue figures as pandas, under a date column type, and the last line starts polars rows=96.
To see the plan Polars built before it ran, print it with explain():
cd ~/tools-demo
uv run python -c "from with_polars import query; print(query.explain())" | tee results/plan.txtImporting with_polars runs the script once more, so its output appears first. In the plan, the CSV scan line is followed by something like PROJECT 4/5 COLUMNS: Polars reads four of the five columns, because the query never uses order_id.
Step 5 · Answer it in DuckDB with SQL
DuckDB is a database that runs inside your Python process, with no server to start. You write SQL, and the FROM clause can name a file directly. DuckDB reads only the columns the query uses and streams through the file rather than loading it first. Create with_duckdb.py:
cd ~/tools-demo
cat > with_duckdb.py <<'PY'
import time
import duckdb
from peak import peak_mb
start = time.perf_counter()
result = duckdb.sql("""
SELECT CAST(date_trunc('month', order_date) AS DATE) AS month,
city,
round(sum(quantity * unit_price), 2) AS revenue
FROM 'sales.csv'
GROUP BY month, city
ORDER BY month, city
""").to_arrow_table()
seconds = time.perf_counter() - start
duckdb.sql("COPY (SELECT * FROM result) TO 'results/duckdb.parquet' (FORMAT parquet)")
print(duckdb.sql("SELECT * FROM result LIMIT 3"))
print(f"duckdb rows={result.num_rows} {seconds:.2f} s peak {peak_mb():.0f} MB")
PY
uv run with_duckdb.pyTwo details are worth knowing. date_trunc returns a TIMESTAMP even when you give it a date, so the CAST(... AS DATE) turns month back into a date to match Polars. And the COPY line queries result, which is an Arrow table in a Python variable, by its name: DuckDB can read pandas, Polars and Arrow tables in scope this way.
Check it worked
The printed table has the same three January rows and revenues, with month as date and city as varchar, and the last line starts duckdb rows=96. ls results lists duckdb.parquet, pandas.parquet and polars.parquet.
Step 6 · Prove the three answers match
Fast and wrong is no use. compare.py loads the three result files, lines them up by month and city with a full join, and reports any row that appears in only one, plus the largest difference in revenue. Sums of floating-point numbers can differ in the last digits when they are added in a different order, which is why the scripts round to cents and the check looks at the gap rather than exact equality:
cd ~/tools-demo
cat > compare.py <<'PY'
import polars as pl
answers = {}
for name in ("pandas", "polars", "duckdb"):
df = pl.read_parquet(f"results/{name}.parquet")
print(f"{name:7} {df.height} rows, month stored as {df.schema['month']}")
answers[name] = df.with_columns(pl.col("month").cast(pl.Date))
base = answers["polars"]
for name in ("pandas", "duckdb"):
joined = base.join(answers[name], on=["month", "city"], how="full", suffix="_other")
gap = (joined["revenue"] - joined["revenue_other"]).abs().max()
missing = joined["revenue"].null_count() + joined["revenue_other"].null_count()
print(f"{name} vs polars: {missing} unmatched rows, largest gap {gap:.2f}")
print(f"total revenue for 2025: {base['revenue'].sum():,.2f}")
PY
uv run compare.py | tee results/compare.txtCheck it worked
Both comparison lines read 0 unmatched rows, largest gap 0.00, and the total is 245,988,300.35. The first three lines show a real difference between the tools: pandas stored month as a datetime, while Polars and DuckDB stored a date. That kind of type mismatch breaks joins in real projects, so it is worth spotting here.
Step 7 · Time all three and check memory under a budget
Run the three scripts twice in a row. The first round can be slower while the operating system loads the file from disk into its cache, so compare the second:
cd ~/tools-demo
for round in 1 2; do
for tool in pandas polars duckdb; do
uv run "with_$tool.py" | tail -n 1
done
doneOn one 8-core Apple M2 laptop with 16 GB of RAM, the second round gave pandas about 0.6 s and 458 MB, Polars about 0.08 s and 210 MB, and DuckDB about 0.3 s and 168 MB. Those are one machine's numbers. On a laptop with 2 or 4 cores the gaps grow or shrink, and the order can change. Trust your own.
pandas needed about six times the file's size in memory because it loaded every column first. At that ratio a 500 MB CSV would need around 3 GB, more than a 4 GB laptop usually has free once the operating system and a browser are running. Polars and DuckDB can both work inside a budget. Polars has a streaming engine that processes the file in batches, and DuckDB has a memory_limit setting and spills to a temporary folder on disk when a query needs more than that. Create polars_streaming.py and duckdb_budget.py:
cd ~/tools-demo
cat > polars_streaming.py <<'PY'
import time
import polars as pl
from peak import peak_mb
start = time.perf_counter()
result = (
pl.scan_csv("sales.csv", try_parse_dates=True)
.group_by("city")
.agg(
orders=pl.len(),
revenue=(pl.col("quantity") * pl.col("unit_price")).sum().round(2),
)
.sort("city")
.collect(engine="streaming")
)
seconds = time.perf_counter() - start
with pl.Config(float_precision=2, tbl_hide_dataframe_shape=True, tbl_rows=8):
print(result)
print(f"polars (streaming) {seconds:.2f} s peak {peak_mb():.0f} MB")
PY
cat > duckdb_budget.py <<'PY'
import time
import duckdb
from peak import peak_mb
con = duckdb.connect()
con.sql("SET memory_limit = '128MB'")
con.sql("SET temp_directory = 'duckdb_tmp'")
con.sql("SET threads = 2")
start = time.perf_counter()
by_city = con.sql("""
SELECT city, count(*) AS orders, round(sum(quantity * unit_price), 2) AS revenue
FROM 'sales.csv'
GROUP BY city
ORDER BY city
""").to_arrow_table()
distinct = con.sql("SELECT count(DISTINCT order_id) FROM 'sales.csv'").fetchall()[0][0]
seconds = time.perf_counter() - start
print(con.sql("SELECT current_setting('memory_limit') AS memory_limit"))
print(con.sql("SELECT * FROM by_city"))
print(f"distinct order ids: {distinct:,}")
print(f"duckdb (128MB limit) {seconds:.2f} s peak {peak_mb():.0f} MB")
PY
uv run polars_streaming.py | tee results/streaming.txt
uv run duckdb_budget.py | tee results/budget.txtmemory_limit caps DuckDB's own working memory, not the whole Python process, so the peak the script reports is higher than 128 MB. When the limit is too tight for the number of threads, DuckDB stops with an Out of Memory Error that suggests lowering threads or raising the limit. That is why the script sets two threads.
Check it worked
Both scripts print the same eight-city table: Lagos has 250,477 orders, and the order counts add up to 2,000,000. The DuckDB script also prints its limit as 122.0 MiB (it reads 128MB as 128,000,000 bytes and displays the limit in mebibytes) and distinct order ids: 2,000,000. In the timing loop, the second round's lines are your own numbers to compare with the sample above.
Step 8 · Move data between the libraries with Arrow
You rarely have to pick only one. A common pattern is to do the heavy reading in Polars or DuckDB and hand a small result to pandas for a library that expects it, such as a plotting or statistics package. All three speak Arrow, so the hand-off is one call. Create arrow_handoff.py:
cd ~/tools-demo
cat > arrow_handoff.py <<'PY'
import duckdb
import polars as pl
monthly = pl.read_parquet("results/polars.parquet")
# Polars to Arrow to pandas.
table = monthly.to_arrow()
as_pandas = table.to_pandas()
print("pandas columns:", dict(as_pandas.dtypes.astype(str)))
# DuckDB reads the pandas DataFrame by its Python variable name.
top = duckdb.sql("""
SELECT city, round(sum(revenue), 2) AS year_revenue
FROM as_pandas
GROUP BY city
ORDER BY year_revenue DESC
LIMIT 3
""")
print(top)
# And back out again in whichever shape the next step needs.
print("to Polars:", type(top.pl()).__name__, "| to pandas:", type(top.df()).__name__,
"| to Arrow:", type(top.to_arrow_table()).__name__)
print("Arrow round trip unchanged:", pl.from_arrow(table).equals(monthly))
PY
uv run arrow_handoff.py | tee results/handoff.txtCheck it worked
DuckDB lists the top three cities for the year, with Lagos first at about 30.8 million, and the last line reads Arrow round trip unchanged: True. Look at the pandas columns line: month arrived as object, because pandas has no plain date type and holds Python date objects instead. Convert it with pd.to_datetime if you need date maths in pandas.
Which one to reach for
- pandas when the data fits comfortably in memory (up to a few hundred MB) and you need the widest ecosystem: scikit-learn, statsmodels, seaborn, Excel files, and most answers online assume pandas.
- Polars when you are building a pipeline of transformations you will rerun, want it fast on every core, and like expressions on named columns. Lazy queries and the streaming engine handle files larger than you would load into pandas.
- DuckDB when you or your team think in SQL, the data lives in CSV or Parquet files, perhaps larger than memory, and you want to query them where they are without loading them first.
When you are unsure, start in DuckDB or Polars for the heavy step and hand the small result to pandas through Arrow, as you did in the last step. To remove everything this tutorial created, delete ~/tools-demo.
Next steps
- Learn Polars expressions and lazy queries properly: get started with Polars.
- Query CSV and Parquet files in place with SQL: query CSV and Parquet files with DuckDB.
- Tidy a messy file with the library most other tools expect: clean a CSV file with pandas.
Part of these paths
Related tutorials
- Get started with Polars expressions and lazy queriesYou will load a shop's orders into Polars 2.2, filter, add columns, group and join them with expressions, then rerun the same report as a lazy query and read the plan Polars optimised.
- Query CSV and Parquet files with SQL in DuckDBYou will query three monthly sales CSV files in place with DuckDB 2.0 SQL, pin the type of a code column so detection cannot change it, save the cleaned result as Parquet, join it to a pandas DataFrame from Python and keep the data in a persistent .duckdb file.
- How to Clean and Summarise a CSV File with pandasYou will take a messy orders CSV with stray spaces, mixed spellings, money written as text, odd dates, missing values and a duplicate row, and clean it with pandas 3.1 on Python 3.15 into a tidy file plus per-country and per-month summaries.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials