Sub topic 8
The same aggregation in all four tools
This chapter assumes you can read basic Python and SQL and have loaded a dataset with pandas or SQL before. It also assumes you know the earlier chapters' terms: eager versus lazy execution, single-node versus distributed, and columnar formats such as Parquet.
You will run one task in pandas, Polars, DuckDB, and Spark: total revenue per region from a Parquet file. The task is simple on purpose. The differences you see come from how each tool works, not from the problem.
The task and the test file
The task has three steps: read region and revenue from sales.parquet, group by region, and sum revenue. The file has a few rows, including one null region, so you can see how each tool handles missing keys.
import pandas as pd
df = pd.DataFrame(
{
"region": ["eu", "us", "eu", "apac", None],
"revenue": [10, 20, 5, 7, 3],
}
)
df.to_parquet("sales.parquet", index=False)This needs pyarrow (or fastparquet) installed, because pandas delegates Parquet writing to one of them. Every example below reads the same file.
pandas: eager and in memory
import pandas as pd
df = pd.read_parquet("sales.parquet", columns=["region", "revenue"])
result = df.groupby("region", as_index=False)["revenue"].sum()
print(result)read_parquet loads the selected columns into RAM at once. groupby(...).sum() then runs immediately on that in-memory data. Passing columns= means only those two columns are read from disk, but pandas does not push any other work into the file read for you.
Each line runs when you reach it, so you can inspect df after the read and result after the aggregation. That makes debugging easy, and it is the main reason pandas is the default for exploration.
Polars: lazy query, one `collect()`
import polars as pl
result = (
pl.scan_parquet("sales.parquet")
.group_by("region")
.agg(pl.col("revenue").sum())
.collect()
)
print(result)scan_parquet does not read the data. It returns a LazyFrame, which is a description of a query. Nothing runs until collect(). At that point Polars optimizes the whole plan, for example by reading only the columns the query uses, and then executes it using multiple threads.
You can look at the plan before running anything:
import polars as pl
lf = (
pl.scan_parquet("sales.parquet")
.filter(pl.col("revenue") > 0)
.select("region", "revenue")
)
print(lf.explain())The printed plan shows the optimizer's decisions, such as which columns the scan will read and where the filter is applied. Reading explain() output is the quickest way to learn what a lazy engine will do.
DuckDB: SQL inside your Python process
import duckdb
result = duckdb.sql(
"SELECT region, sum(revenue) AS revenue "
"FROM 'sales.parquet' GROUP BY region"
).df()
print(result)DuckDB runs inside the Python process. There is no server to start. The FROM 'sales.parquet' clause tells it to read the file directly, and .df() converts the result to a pandas DataFrame. If you leave off .df(), you get a DuckDB relation that you can keep querying.
You describe the result in SQL, and DuckDB's optimizer decides how to execute it. If you already think in SQL, this is the lowest-friction option of the four.
Spark: a distributed plan, started by an action
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.appName("sales").getOrCreate()
result = (
spark.read.parquet("sales.parquet")
.groupBy("region")
.agg(F.sum("revenue").alias("revenue"))
)
result.show()Spark builds a lazy plan. show() is an action that triggers execution across the executors, which are the worker processes. Here, in local mode, they run on your own machine. The code is nearly identical whether the file is 5 rows or 5 terabytes, and that portability is Spark's main selling point. On this tiny file, though, most of the run time goes to starting the JVM (Java Virtual Machine) and the Spark session, not to the aggregation.
How the four runs differ
| Aspect | pandas | Polars (lazy) | DuckDB | Spark |
|---|---|---|---|---|
| Style | Python method calls | Python expressions | SQL | Python DataFrame API (or SQL) |
| When work runs | At each line | At `collect()` | When the query executes | At an action such as `show()` |
| Reads only needed columns | Only if you pass `columns=` | Automatically | Automatically | Automatically |
| Startup cost | Negligible | Negligible | Negligible | Seconds (JVM and session) |
| Result type | `DataFrame` | Polars `DataFrame` | Relation, then `.df()` | Spark `DataFrame` |
Results are not identical by default
The four outputs look similar on a quick read but differ in details. These differences cause bugs when you migrate code or compare tools.
- Row order. pandas sorts group keys by default. Polars, DuckDB, and Spark do not guarantee any order. Sort explicitly before comparing results, for example with
.sort("region")in Polars,ORDER BY regionin SQL, or.orderBy("region")in Spark. - Null group keys. pandas drops rows whose key is null, because
groupbydefaults todropna=True. Polars, DuckDB, and Spark keep a separate group for nulls. On the test file, pandas returns three groups and the other three tools return four. - Sum of all-null values. SQL semantics (DuckDB, Spark) give
NULLfor a sum over only nulls. pandas and Polars give0. - Output types. An integer column can come back as
int64,Int64, orBIGINT, and a SQLsumover integers may widen the type. Check dtypes if the result feeds other code.
To make pandas match the others on null keys, pass dropna=False:
import pandas as pd
df = pd.read_parquet("sales.parquet", columns=["region", "revenue"])
result = df.groupby("region", as_index=False, dropna=False)["revenue"].sum()
print(result.sort_values("region", na_position="last"))What this tells you about choosing
On a file that fits in memory, all four tools return the right answer in well under a second of actual computation. The choice at this scale is about ergonomics and cost:
- pandas gives you step-by-step inspection and the widest library support.
- Polars gives you the same DataFrame style with automatic column pruning and parallel execution.
- DuckDB lets you reuse SQL skills and query files without loading them yourself.
- Spark carries a fixed startup cost that pays off only when the data or the cluster is large.
Differences in speed and memory show up as the data grows. The chapters on memory limits, distribution costs, and benchmarking cover that. Do not extrapolate from a five-row file.
Exercise
You port the pandas aggregation to Polars and find that the Polars result has one more row than the pandas result. The extra row has a null region. What explains this, and how do you make the pandas version match?
Show answer
pandas groupby drops null keys by default (dropna=True), while Polars keeps them as their own group. Pass dropna=False to groupby in pandas so the null group is kept. Then sort both results by region before comparing, because Polars does not guarantee row order.
Exercise
In the Polars example, which call actually reads and aggregates the data, and why can the optimizer read fewer columns than the file contains?
Show answer
collect() runs the query. Before that, scan_parquet, group_by, and agg only build a plan. Because the optimizer sees the whole plan, it knows only region and revenue are needed and reads just those columns from the Parquet file.