Sub topic 12
Grouping and aggregating
This chapter assumes you can create a DataFrame, select and filter columns, and add derived columns with withColumn. It uses the orders DataFrame from earlier chapters, in a Databricks notebook where spark already exists.
The working model
Aggregation reduces many rows to fewer rows. groupBy splits the rows into groups by the key columns. agg then computes one result per group. The result has one row per distinct key, plus the aggregate columns you ask for.
groupBy alone returns a grouped object, not a DataFrame. Nothing runs until you call agg (or a shortcut such as count) and then an action such as display or show.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))
summary = (
orders
.groupBy("customer")
.agg(
F.count("*").alias("order_count"),
F.sum("amount").alias("total_amount"),
F.avg("amount").alias("avg_amount"),
)
.orderBy(F.col("total_amount").desc())
)
display(summary)Always put several aggregates in one agg call. Each call to agg is one pass over the data, and one name per result column keeps the output readable. Use alias on each aggregate. Without it, Spark names columns like sum(amount), which are awkward to reference later.
How nulls behave
sum, avg, min and max skip null values. count("*") counts every row. count("amount") counts only rows where amount is not null.
In the example, carol has one order with a null amount. Her order_count is 1, but her total_amount and avg_amount are null, because every value in her group is null. If you want zero instead, wrap the result with F.coalesce(F.sum("amount"), F.lit(0.0)).
| Expression | Counts or uses | Carol's result |
|---|---|---|
| `F.count("*")` | All rows | 1 |
| `F.count("amount")` | Non-null amounts | 0 |
| `F.sum("amount")` | Non-null amounts | null |
What happens inside
Rows with the same key must end up on the same machine, so Spark moves data between executors. This move is a shuffle. Spark first computes partial aggregates on each partition, which shrinks the data before the shuffle, then merges the partials. A later chapter shows how to find the shuffle in a query plan.
Common errors
- Selecting a column that is not in the group key or an aggregate. After
groupBy("customer"), a column likeorder_dateis gone unless you aggregate it, for example withF.max("order_date"). - Forgetting that the output order is not guaranteed. Add
orderBywhen order matters. - Using
counton a grouped object and expecting a named column. It produces a column calledcount. Preferaggwith an alias. - Grouping on a column with very many distinct values. This produces a large result and an expensive shuffle.
Exercise
Using orders, write a query that returns, for each month, the number of orders and the largest amount. Which functions would you use to get the month?
Show answer
Derive a month column with F.datetrunc("month", "orderdate") or F.month("orderdate"), then group on it: orders.withColumn("month", F.datetrunc("month", "orderdate")).groupBy("month").agg(F.count("*").alias("ordercount"), F.max("amount").alias("max_amount")). The max skips null amounts.