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 also assumes you know that transformations are lazy and actions run them. Here you will summarize rows with groupBy and agg, and learn how nulls and shuffles affect the result.
What aggregation does
An aggregation collapses many rows into fewer rows. groupBy splits the data into groups by the values of one or more columns. agg then computes one value per group for each aggregate function you list. The result is a new DataFrame with one row per group.
Spark runs this in two steps. Each partition first computes partial results for the groups it holds. Spark then moves the partial results for each group to the same place, which is a shuffle, and merges them.
A grouped summary
The examples use the orders DataFrame from earlier chapters. It has order_id, customer, order_date (a date) and amount. Carol's amount is null.
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",
).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)The result has three rows, one per customer:
| customer | order_count | total_amount | avg_amount |
|---|---|---|---|
| alice | 2 | 150.0 | 75.0 |
| bob | 1 | 75.5 | 75.5 |
| carol | 1 | null | null |
Three details matter here.
- You can pass several aggregates to one
aggcall. Spark computes them in a single pass over the data. aliasnames each output column. Without it, Spark generates names such assum(amount), which are awkward to reference later.groupByis lazy. Nothing runs until an action such asdisplayorshow.
Nulls in aggregates
Most aggregate functions ignore null values. Carol has one order with a null amount, so the behavior differs by function:
F.count("*")counts every row, so Carol has a count of 1.F.count("amount")counts only non-null values, so Carol would have 0.F.sum("amount")andF.avg("amount")skip nulls. If every value in a group is null, the result is null, not 0.F.avgdivides by the number of non-null values, not by the number of rows.
If you want a missing total to appear as 0, wrap the aggregate in coalesce:
safe = (
orders
.groupBy("customer")
.agg(F.coalesce(F.sum("amount"), F.lit(0.0)).alias("total_amount"))
)
display(safe)Common aggregate functions
| Function | Result |
|---|---|
| `count`, `countDistinct` | Number of rows, or of distinct non-null values |
| `sum`, `avg` | Total and mean of non-null values |
| `min`, `max` | Smallest and largest value |
| `first`, `last` | A value from the group, which depends on row order and is not stable |
| `collect_list`, `collect_set` | An array of all values, or of distinct values |
| `approx_count_distinct` | A fast estimate of distinct values |
Use approx_count_distinct on large data when a small error is acceptable. An exact countDistinct must track every distinct value, which costs more memory and shuffle work.
Use collect_list with care. It builds one array per group in memory. A group with millions of rows can produce a very large value and cause an out-of-memory error on one executor.
Grouping by several columns and by expressions
Pass more than one column to groupBy to group by their combination. You can also group by an expression, such as the month of a date:
monthly = (
orders
.groupBy("customer", F.date_trunc("month", "order_date").alias("month"))
.agg(F.sum("amount").alias("monthly_total"))
.orderBy("customer", "month")
)
display(monthly)Alice has two rows in the result, one for January and one for February. A null in a grouping column forms its own group. Spark does not drop those rows.
Aggregating the whole DataFrame
Call agg directly on the DataFrame to compute one row for the entire dataset:
totals = orders.agg(
F.count("*").alias("rows"),
F.countDistinct("customer").alias("customers"),
F.max("order_date").alias("latest_order"),
)
display(totals)This has no groupBy, so Spark treats all rows as one group.
Conditional aggregates
To count or sum only some rows inside a group, use F.when inside the aggregate. when returns null for rows that do not match, and aggregates skip nulls:
conditional = (
orders
.groupBy("customer")
.agg(
F.sum(F.when(F.col("amount") > 50, 1).otherwise(0)).alias("big_orders"),
F.sum(F.when(F.col("amount") > 50, F.col("amount"))).alias("big_total"),
)
)
display(conditional)For Carol, the comparison amount > 50 evaluates to null, not false. In the first aggregate, otherwise(0) turns that into 0. In the second, no otherwise is given, so the result stays null.
Filtering groups after aggregation
filter after agg plays the role of SQL HAVING. Filter on the aggregated column:
repeat_customers = (
orders
.groupBy("customer")
.agg(F.count("*").alias("order_count"))
.filter(F.col("order_count") > 1)
)
display(repeat_customers)Filter rows before grouping when you can. That condition plays the role of WHERE. It reduces the data that reaches the shuffle, which is cheaper than grouping everything and discarding groups later.
Cost and skew
Grouping triggers a shuffle, so it appears in the plan as an Exchange operator. You can confirm this with explain():
summary.explain()Look for two HashAggregate steps with an Exchange hashpartitioning(customer, ...) between them. The first is the partial aggregate and the second is the final merge. If you see only an aggregate and no exchange, Spark found the data already partitioned by the key.
Aggregation is slow when a few keys hold most of the rows. This is called skew. One task then processes a large group while the others finish early. Signs include one long-running task in the Spark UI and a stage that stays at "199 of 200 tasks" for a long time. Adaptive query execution, which Databricks enables by default, can split some skewed partitions, mainly in joins. Do not rely on it for every aggregate. When one key dominates, check whether you can filter that key out or aggregate in two stages.
Common errors
- A column is neither grouped nor aggregated. Selecting
order_idaftergroupBy("customer").agg(...)fails or is impossible, since the output only holds the group keys and the aggregates. Add the column togroupByor wrap it in an aggregate. - Using Python
suminstead ofF.sum. Python's built-insumdoes not take a column name and gives a confusing error or the wrong result. Importfunctions as Fand useF.sum. - Forgetting
alias. Later code that refers tosum(amount)has to quote an awkward name. - Treating null totals as zero. A group of only nulls returns null. Use
coalescewhen you need a number. - Expecting a stable
first. The value depends on partition order, which can change between runs.
Exercise
Using the orders DataFrame, write code that returns each customer's number of orders with a non-null amount, and keeps only customers with at least one such order. What does Carol's row look like before the filter, and why?
Show answer
Use F.count("amount"), which counts only non-null values, then filter on it.
orders.groupBy("customer").agg(F.count("amount").alias("paidorders")).filter(F.col("paidorders") >= 1)
Before the filter, Carol has paid_orders = 0. She has one row, but its amount is null, and count("amount") skips nulls. The filter then removes her. With count("*") she would have a count of 1 and would stay.
Exercise
Why does groupBy("customer").agg(F.collect_list("order_id")) risk failing on a large table, when F.sum("amount") does not?
Show answer
sum keeps one number per group and can be combined from partial results before the shuffle. collect_list must hold every value of a group in one array, so the shuffle moves much more data and a very large group can exhaust memory on one executor.