Sub topic 8
The same aggregation in all four tools
This chapter assumes you know basic Python, can read a SQL GROUP BY, and have loaded a Parquet file or CSV into a DataFrame before. The task is the same in every tool: read sales.parquet, then total revenue for each region. Comparing the code shows where the tools differ in execution and in style.
The task
The file sales.parquet has at least two columns, region (string) and revenue (number). The result should have one row per region with the summed revenue.
pandas: eager
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 memory right away. groupby(...).sum() then runs immediately on that in-memory data. Passing columns= limits what is loaded, which saves memory. pandas does this only because you asked for it.
Polars: lazy
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 starts a lazy query. Nothing runs until collect(). At that point Polars optimizes the plan, for example by reading only region and revenue, and then executes it.
DuckDB: SQL in process
import duckdb
result = duckdb.sql(
"SELECT region, sum(revenue) AS revenue "
"FROM 'sales.parquet' GROUP BY region"
).df()
print(result)DuckDB runs inside your Python process. It reads the Parquet file directly from the SQL text. The .df() call converts the result to a pandas DataFrame.
Spark: lazy and distributed
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 plan and does not run it until an action such as show() is called. It then executes the plan across its executors. On a laptop it runs in local mode. On a cluster the same code spreads over many machines.
Side by side
| Tool | When work runs | Where it runs | Query style |
|---|---|---|---|
| pandas | Each step, immediately | One process, in memory | Method calls |
| Polars | At `collect()` | One machine, multiple threads | Expressions |
| DuckDB | When the SQL executes | In your Python process | SQL |
| Spark | At an action such as `show()` | Executors, local or cluster | DataFrame API or SQL |
Common errors
- Forgetting the trigger. A Polars
LazyFrameor a Spark DataFrame withoutcollect()orshow()computes nothing. You get a plan object, not data. - Column order and row order. Group-by results are not guaranteed to come back in the same order in every tool. Sort before you compare outputs.
- Starting Spark for small data.
getOrCreate()starts a JVM session. For a file that fits in memory, that startup time often exceeds the query time. - Result types.
.df()in DuckDB returns pandas, whilecollect()in Polars returns a Polars DataFrame. Check the type before you pass it on.
Exercise
You run pl.scan_parquet("sales.parquet").group_by("region").agg(pl.col("revenue").sum()) and print the result. You see a query plan object and no totals. What is missing, and why does Polars behave this way?
Show answer
The call to .collect() is missing. scan_parquet and the later steps only build a lazy query. Polars runs it, after optimization, when you call collect(). Waiting lets it plan the whole query first, for example by reading only the columns it needs.