pandas vs Polars vs SQL
pandas, Polars and DuckDB all transform tables. They differ in how they run: pandas is eager and mostly single-core; Polars plans queries and uses every core; DuckDB is a SQL engine inside your Python process that reads files and DataFrames directly. They also pass data to each other cheaply, so one project often uses two of them. This guide helps you choose, then shows the same tasks in all three. The examples use data/sales.csv (20,228 order lines) and data/stores.csv.
flowchart TD
A{"Where is the data?"} -->|"in a database server"| SQL["SQL in that database:<br/>move the work to the data"]
A -->|"files or DataFrames"| B{"Fits easily in memory?"}
B -->|no| C{"Prefer SQL?"}
C -->|yes| D1["DuckDB on the files"]
C -->|no| D2["Polars lazy, streaming"]
B -->|yes| E{"Next step needs pandas?<br/>plots, statsmodels"}
E -->|yes| P["pandas"]
E -->|no| F{"Speed or a long<br/>pipeline matters?"}
F -->|yes| PL["Polars, or DuckDB for SQL"]
F -->|no| P
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| explore a small table and plot it | pandas | df.groupby("region")["revenue"].sum().plot.bar() |
| feed statsmodels, seaborn or an old tutorial | pandas | smf.ols("y ~ x", data=df) |
| a fast pipeline over large CSV or Parquet files | Polars lazy | pl.scan_parquet("data/*.parquet").filter(...).collect() |
| data larger than memory, in Python code | Polars streaming | lf.collect(engine="streaming") |
| data larger than memory, in SQL | DuckDB | duckdb.sql("SELECT ... FROM 'data/*.parquet'") |
| query a CSV file without loading it first | DuckDB | duckdb.sql("SELECT COUNT(*) FROM 'data/sales.csv'") |
| run SQL on a pandas or Polars frame | DuckDB | duckdb.sql("SELECT ... FROM df"): the variable name is the table |
| run SQL inside Polars | df.sql(...) |
df.sql("SELECT region, SUM(revenue) FROM self GROUP BY region") |
| read from SQLite or PostgreSQL | pd.read_sql_query, pl.read_database |
push filters and joins into the SQL |
| one row per group (top 1) | pandas head(1) after sort; Polars over; SQL QUALIFY |
see task 3 |
| a group total on every row | transform; .over(); SUM() OVER |
see the translation table |
| monthly totals | resample("MS"); dt.truncate("1mo"); date_trunc('month', d) |
see task 4 |
| strict, explicit dtypes | Polars or DuckDB | errors instead of silent casts |
row labels, .loc, MultiIndex |
pandas | Polars and SQL have no index |
| time series with a DatetimeIndex | pandas | asfreq, resample, rolling("7D") |
| a long ETL job with many steps | Polars lazy | one optimized plan |
| ad hoc questions by an SQL-minded team | DuckDB | the query is the documentation |
| convert pandas → Polars | pl.from_pandas(df) |
needs pyarrow |
| convert Polars → pandas | df.to_pandas() |
needs pyarrow |
| a DuckDB result as pandas / Polars | rel.df() / rel.pl() |
|
| scikit-learn output as Polars | set_output(transform="polars") |
before fit |
| NumPy for a model | df.to_numpy() |
all three can hand over arrays |
Comparison
Section titled “Comparison”| pandas 3 | Polars 2 | DuckDB 2 (SQL) | |
|---|---|---|---|
| Execution | eager: each line runs at once | eager, or lazy with a query optimizer | a planned SQL query |
| Cores | mostly one | all | all |
| Memory | the whole frame in RAM; intermediate copies | Arrow columns; streaming engine for larger than RAM | columnar; spills to disk when RAM runs out |
| Syntax | methods, [], .loc, the index |
expressions: pl.col("x").sum().over("g") |
SQL: SUM(x) OVER (PARTITION BY g) |
| Row labels | an index (often a source of bugs) | none | none |
| Missing values | NaN, NA; integers become floats in some operations |
null, separate from NaN |
NULL, three-valued logic |
| Strings | str dtype (Arrow-backed) |
String (Arrow) |
VARCHAR |
| Types | flexible, some silent casts | strict; errors on mismatch | strict |
| Files | read into memory | read_* or lazy scan_* (CSV, Parquet, NDJSON) |
queries CSV, Parquet, JSON and globs in place |
| Ecosystem | everywhere: Matplotlib, seaborn, statsmodels, scikit-learn | growing; converts to pandas cheaply | any tool that speaks SQL; returns pandas or Polars |
| Best for | small to medium data, exploration, plots, time series | pipelines on large files, ETL, speed | ad hoc analysis on files, joins, Parquet folders, SQL teams |
| Weak at | speed and memory on large data; row loops | niche operations, fewer tutorials | step-by-step row logic, complex reshaping |
Rough sizes: pandas is comfortable up to a few million rows (under about a fifth of your RAM). Polars and DuckDB stay fast to hundreds of millions of rows, and both can work through data larger than memory.
The same tasks in each
Section titled “The same tasks in each”import duckdbimport pandas as pdimport polars as pl
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)pl.Config.set_tbl_width_chars(100)pl.Config.set_tbl_hide_column_data_types(True)
sales_pd = pd.read_csv("data/sales.csv", parse_dates=["order_date"])stores_pd = pd.read_csv("data/stores.csv")sales_pl = pl.read_csv("data/sales.csv", try_parse_dates=True)stores_pl = pl.read_csv("data/stores.csv")DuckDB reads the CSV files directly by path. It could also query sales_pd or sales_pl by their variable names.
Task 1: group, aggregate and sort
Section titled “Task 1: group, aggregate and sort”Orders and revenue per region and channel, the four largest:
task1 = ( sales_pd.groupby(["region", "channel"], as_index=False) .agg(orders=("order_id", "count"), revenue=("revenue", "sum")) .sort_values("revenue", ascending=False) .head(4))print(task1) region channel orders revenue1 East store 3119 567352.793 North store 2822 510539.535 South store 3021 508161.627 West store 2771 491003.42task1 = ( sales_pl.group_by("region", "channel") .agg(orders=pl.len(), revenue=pl.col("revenue").sum().round(2)) .sort("revenue", descending=True) .head(4))print(task1)shape: (4, 4)┌────────┬─────────┬────────┬───────────┐│ region ┆ channel ┆ orders ┆ revenue │╞════════╪═════════╪════════╪═══════════╡│ East ┆ store ┆ 3119 ┆ 567352.79 ││ North ┆ store ┆ 2822 ┆ 510539.53 ││ South ┆ store ┆ 3021 ┆ 508161.62 ││ West ┆ store ┆ 2771 ┆ 491003.42 │└────────┴─────────┴────────┴───────────┘task1 = duckdb.sql(""" SELECT region, channel, COUNT(*) AS orders, ROUND(SUM(revenue), 2) AS revenue FROM 'data/sales.csv' GROUP BY ALL ORDER BY revenue DESC LIMIT 4""").df()print(task1) region channel orders revenue0 East store 3119 567352.791 North store 2822 510539.532 South store 3021 508161.623 West store 2771 491003.42Task 2: filter, join and rank
Section titled “Task 2: filter, join and rank”2024 revenue per city (from the stores table), top 3:
task2 = ( sales_pd[sales_pd["order_date"].dt.year == 2024] .merge(stores_pd[["store_id", "city"]], on="store_id", how="left") .groupby("city", as_index=False)["revenue"].sum() .nlargest(3, "revenue"))print(task2) city revenue8 New York 263924.002 Chicago 220899.0811 Seattle 213238.50task2 = ( sales_pl.filter(pl.col("order_date").dt.year() == 2024) .join(stores_pl.select("store_id", "city"), on="store_id", how="left") .group_by("city") .agg(pl.col("revenue").sum().round(2)) .sort("revenue", descending=True) .head(3))print(task2)shape: (3, 2)┌──────────┬───────────┐│ city ┆ revenue │╞══════════╪═══════════╡│ New York ┆ 263924.0 ││ Chicago ┆ 220899.08 ││ Seattle ┆ 213238.5 │└──────────┴───────────┘task2 = duckdb.sql(""" SELECT st.city, ROUND(SUM(s.revenue), 2) AS revenue FROM 'data/sales.csv' AS s LEFT JOIN 'data/stores.csv' AS st USING (store_id) WHERE year(s.order_date) = 2024 GROUP BY st.city ORDER BY revenue DESC LIMIT 3""").df()print(task2) city revenue0 New York 263924.001 Chicago 220899.082 Seattle 213238.50Task 3: the top row in each group
Section titled “Task 3: the top row in each group”The best-selling product of each category by revenue, a window-function task:
per_product = sales_pd.groupby(["category", "product"], as_index=False)["revenue"].sum()task3 = ( per_product.sort_values(["category", "revenue"], ascending=[True, False]) .groupby("category") .head(1) # first row of each group after the sort)print(task3.to_string(index=False)) category product revenue Beauty Electric Toothbrush 43618.57 Books Statistics Made Simple 31270.35 Clothing Waterproof Rain Jacket 104660.50Electronics 14-inch Ultrabook Laptop 665328.45 Home Espresso Machine 197987.70 Sports Adjustable Dumbbells 165084.30task3 = ( sales_pl.group_by("category", "product") .agg(pl.col("revenue").sum().round(2)) .filter(pl.col("revenue") == pl.col("revenue").max().over("category")) .sort("category"))print(task3)shape: (6, 3)┌─────────────┬──────────────────────────┬───────────┐│ category ┆ product ┆ revenue │╞═════════════╪══════════════════════════╪═══════════╡│ Beauty ┆ Electric Toothbrush ┆ 43618.57 ││ Books ┆ Statistics Made Simple ┆ 31270.35 ││ Clothing ┆ Waterproof Rain Jacket ┆ 104660.5 ││ Electronics ┆ 14-inch Ultrabook Laptop ┆ 665328.45 ││ Home ┆ Espresso Machine ┆ 197987.7 ││ Sports ┆ Adjustable Dumbbells ┆ 165084.3 │└─────────────┴──────────────────────────┴───────────┘task3 = duckdb.sql(""" SELECT category, product, ROUND(SUM(revenue), 2) AS revenue FROM 'data/sales.csv' GROUP BY category, product QUALIFY ROW_NUMBER() OVER (PARTITION BY category ORDER BY SUM(revenue) DESC) = 1 ORDER BY category""").df()print(task3.to_string(index=False)) category product revenue Beauty Electric Toothbrush 43618.57 Books Statistics Made Simple 31270.35 Clothing Waterproof Rain Jacket 104660.50Electronics 14-inch Ultrabook Laptop 665328.45 Home Espresso Machine 197987.70 Sports Adjustable Dumbbells 165084.30Task 4: monthly totals and the change from the previous month
Section titled “Task 4: monthly totals and the change from the previous month”The first four months of 2024:
monthly = sales_pd.set_index("order_date")["revenue"].resample("MS").sum()task4 = pd.DataFrame({"revenue": monthly, "change": monthly.pct_change()})print(task4.loc["2024-01":"2024-04"].round(3)) revenue changeorder_date2024-01-01 119596.89 -0.5042024-02-01 106320.41 -0.1112024-03-01 145567.22 0.3692024-04-01 114917.50 -0.211task4 = ( sales_pl.group_by(month=pl.col("order_date").dt.truncate("1mo")) .agg(pl.col("revenue").sum()) .sort("month") .with_columns(change=pl.col("revenue").pct_change().round(3)) .with_columns(pl.col("revenue").round(2)) .filter(pl.col("month").dt.year() == 2024) .head(4))print(task4)shape: (4, 3)┌────────────┬───────────┬────────┐│ month ┆ revenue ┆ change │╞════════════╪═══════════╪════════╡│ 2024-01-01 ┆ 119596.89 ┆ -0.504 ││ 2024-02-01 ┆ 106320.41 ┆ -0.111 ││ 2024-03-01 ┆ 145567.22 ┆ 0.369 ││ 2024-04-01 ┆ 114917.5 ┆ -0.211 │└────────────┴───────────┴────────┘task4 = duckdb.sql(""" WITH m AS ( SELECT date_trunc('month', order_date) AS month, SUM(revenue) AS revenue FROM 'data/sales.csv' GROUP BY ALL ) SELECT month, ROUND(revenue, 2) AS revenue, ROUND(revenue / LAG(revenue) OVER (ORDER BY month) - 1, 3) AS change FROM m ORDER BY month""").df()print(task4[task4["month"].dt.year == 2024].head(4).to_string(index=False)) month revenue change2024-01-01 119596.89 -0.5042024-02-01 106320.41 -0.1112024-03-01 145567.22 0.3692024-04-01 114917.50 -0.211Lazy and out-of-core work
Section titled “Lazy and out-of-core work”Polars’ lazy API and DuckDB both read only the columns and rows a query needs. pandas reads the whole file unless you say otherwise:
lazy = ( pl.scan_csv("data/sales.csv") # nothing is read yet .filter(pl.col("channel") == "online") .group_by("category") .agg(pl.col("revenue").sum().round(2)) .sort("revenue", descending=True))print(lazy.head(2).collect()) # the optimizer reads only 3 columnsonline = duckdb.sql(""" SELECT COUNT(*) FROM 'data/sales.csv' WHERE channel = 'online'""").fetchall()print(online)cols = pd.read_csv("data/sales.csv", usecols=["channel", "revenue"]) # pandas: by handprint(cols.shape)shape: (2, 2)┌─────────────┬───────────┐│ category ┆ revenue │╞═════════════╪═══════════╡│ Electronics ┆ 767072.48 ││ Home ┆ 284066.0 │└─────────────┴───────────┘[(8495,)](20228, 2)| Tool | Larger than memory |
|---|---|
| pandas | read_csv(..., chunksize=100_000) and combine partial results by hand; or switch tools |
| Polars | pl.scan_csv / pl.scan_parquet, then collect(engine="streaming") or sink_parquet(...) |
| DuckDB | queries files in place; spills to disk; COPY (SELECT ...) TO 'out.parquet' |
Translation table
Section titled “Translation table”| Task | pandas | Polars | SQL (DuckDB) |
|---|---|---|---|
| select columns | df[["a", "b"]] |
df.select("a", "b") |
SELECT a, b |
| filter rows | df[df["a"] > 5], df.query("a > 5") |
df.filter(pl.col("a") > 5) |
WHERE a > 5 |
| new column | df.assign(c=df["a"] * 2) |
df.with_columns(c=pl.col("a") * 2) |
SELECT *, a * 2 AS c |
| if/else column | np.where(cond, x, y) |
pl.when(cond).then(x).otherwise(y) |
CASE WHEN cond THEN x ELSE y END |
| sort | df.sort_values("a", ascending=False) |
df.sort("a", descending=True) |
ORDER BY a DESC |
| group and aggregate | df.groupby("g").agg(t=("x", "sum")) |
df.group_by("g").agg(t=pl.col("x").sum()) |
SELECT g, SUM(x) AS t ... GROUP BY g |
| count rows per group | df.groupby("g").size() |
df.group_by("g").len() |
COUNT(*) ... GROUP BY g |
| filter groups | filter the aggregated frame | .filter(...) after agg |
HAVING COUNT(*) > 10 |
| group total on each row | df.groupby("g")["x"].transform("sum") |
pl.col("x").sum().over("g") |
SUM(x) OVER (PARTITION BY g) |
| rank in a group (ties share the lowest rank) | df.groupby("g")["x"].rank(method="min", ascending=False) |
pl.col("x").rank("min", descending=True).over("g") |
RANK() OVER (PARTITION BY g ORDER BY x DESC) |
| previous row | df.sort_values(["g", "d"]).groupby("g")["x"].shift() |
df.sort("g", "d"), then pl.col("x").shift().over("g") |
LAG(x) OVER (PARTITION BY g ORDER BY d) |
| running total | df.sort_values(["g", "d"]).groupby("g")["x"].cumsum() |
df.sort("g", "d"), then pl.col("x").cum_sum().over("g") |
SUM(x) OVER (PARTITION BY g ORDER BY d ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) |
| left join | a.merge(b, on="k", how="left") |
a.join(b, on="k", how="left") |
a LEFT JOIN b USING (k) |
| rows without a match | a[~a["k"].isin(b["k"])] |
a.join(b, on="k", how="anti") |
WHERE NOT EXISTS (...), ANTI JOIN |
| stack frames | pd.concat([a, b]) |
pl.concat([a, b]) |
UNION ALL |
| distinct | df.drop_duplicates() |
df.unique(maintain_order=True) |
SELECT DISTINCT |
| long to wide | df.pivot_table(index="r", columns="c", values="v", aggfunc="sum") |
df.pivot(on="c", index="r", values="v", aggregate_function="sum") |
PIVOT t ON c USING SUM(v) GROUP BY r |
| wide to long | df.melt(id_vars="k") |
df.unpivot(index="k") |
UNPIVOT t ON COLUMNS(* EXCLUDE (k)) |
| fill missing | df["x"].fillna(0) |
pl.col("x").fill_null(0) |
COALESCE(x, 0) |
| month of a date | df["d"].dt.to_period("M") |
pl.col("d").dt.truncate("1mo") |
date_trunc('month', d) |
pandas and Polars window operations follow the current row order, so sort first; SQL states the order in OVER. Without ROWS BETWEEN ..., SUM(x) OVER (... ORDER BY d) uses a RANGE frame: rows tied on d are added in one step, unlike cumsum.
Moving data between them
Section titled “Moving data between them”| From → to | Code | Cost |
|---|---|---|
| pandas → Polars | pl.from_pandas(df) |
cheap for numeric columns (Arrow) |
| Polars → pandas | df.to_pandas() |
cheap with pyarrow |
| pandas or Polars → DuckDB | duckdb.sql("SELECT ... FROM df") |
no copy: DuckDB scans the frame |
| DuckDB → pandas / Polars | .df() / .pl() |
one conversion of the result |
| SQLite → pandas / Polars | pd.read_sql_query(sql, con), pl.read_database(sql, connection=con) |
the database does the filtering |
| any → NumPy | df.to_numpy(), rel.fetchnumpy() |
|
| any → Parquet | df.to_parquet(p), df.write_parquet(p), COPY ... TO 'p.parquet' |
the best format to share between tools |
A common split: DuckDB or Polars to filter and aggregate the big data, then .to_pandas() on the small result for plots and statsmodels.
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
| a pandas result with a group index | columns missing after groupby; odd joins |
as_index=False or reset_index() |
| pandas index alignment | NaN after assigning a Series from another frame | align on keys with merge, or use .to_numpy() |
Polars group_by order |
the row order changes between runs | .sort(...) or maintain_order=True |
Polars top_k order |
not guaranteed to be sorted | .sort(...).head(k) |
pl.count() for rows |
TypeError in Polars 2 |
pl.len() |
| pandas tutorials in Polars | AttributeError: groupby, melt removed |
group_by, unpivot; see the Polars page |
| NULL in SQL comparisons | WHERE x <> 'a' drops NULL rows |
x IS DISTINCT FROM 'a', or COALESCE |
NaN vs null in Polars |
fill_null does not touch NaN |
fill_nan(None) first, or fill_nan(0) |
| integer column with missing values in pandas | it becomes float | Int64 (nullable) dtype |
duckdb.sql(...) treated as data |
a relation, not rows; fetchone() does not exist in DuckDB 2 |
.df(), .pl() or .fetchall() |
DuckDB "text" in double quotes |
Binder Error: a column name |
single quotes for strings |
| integer division | 7 / 2 is 3 in SQLite, 3.5 in DuckDB |
// in DuckDB; CAST in SQLite |
to_pandas() or from_pandas() |
ModuleNotFoundError: pyarrow |
pip install pyarrow |
row-by-row apply in pandas or map_elements in Polars |
100× slower than an expression | vectorized column expressions |
| collecting a huge lazy result | out of memory at collect() |
aggregate first, or sink_parquet |
| benchmarks on tiny data | pandas looks as fast as Polars | measure on realistic sizes; choose for clarity on small data |
| string matching across tools | LIKE is case-sensitive in DuckDB, not in SQLite |
ILIKE in DuckDB; .str.contains("x", case=False) in pandas |
Learn more
Section titled “Learn more”- Module 24: pandas fundamentals and module 25: pandas advanced, with their fundamentals and advanced cheat sheets
- Module 30: SQL for data analysis and its cheat sheet
- Module 31: Polars and its cheat sheet
- Master cheat sheet: pandas, Polars, SQL and DuckDB