groupBy + agg
"Revenue per city", "orders per customer", "average delivery time per restaurant": summaries like these are most of analytics. groupBy and agg produce them. This lesson shows how rows become one row per group, the different ways of counting, filtering on a total, and why Spark does it cheaply.
Step 1 · PySpark functions · Bronze · Combine and summarise, lesson 1 of 4
On this page
Show code in
Every code block on the page follows this.
Read first: select · filter / where (skip if you know them)
In plain words first
Picture a pile of receipts from many cities. You sort them into one pile per city, then write one number on top of each pile: the total. The individual receipts are gone; one line per city is left.
groupBy is the sorting into piles, and agg is what you write on top: a sum, a count, an average, or several at once.
What it does
groupBy on its own returns a GroupedData object, not a DataFrameDataFrame: A table of rows and named columns that Spark processes in parallel. It never changes: every operation returns a new one. Learn more →. Calling agg (or a shortcut like count()) finishes the job and returns a DataFrame with the grouping columns followed by the aggregates.
Step by step
employees
| name | dept | salary |
|---|---|---|
| Asha | Engineering | 72000 |
| Chitra | Engineering | 95000 |
| Ben | Sales | 48000 |
| Esha | Sales | 50000 |
| Dev | HR | 51000 |
Output
| dept | people | avg_salary |
|---|---|---|
| Engineering | 2 | 83500 |
| Sales | 2 | 49000 |
| HR | 1 | 51000 |
- 1Rows are split into groups by the key, here
dept. - 2Each aggregate is computed per group:
countcounts rows,avgaverages non-nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → salaries. - 3The output has one row per group. Output order is not guaranteed: add
orderByif you need one.
Run the example
Input: employees
| id | name | dept | salary | manager_id |
|---|---|---|---|---|
| 1 | Asha | Engineering | 72000 | null |
| 2 | Ben | Sales | 48000 | 1 |
| 3 | Chitra | Engineering | 95000 | 1 |
| 4 | Dev | HR | 51000 | 1 |
| 5 | Esha | Sales | 50000 | 2 |
| 6 | Farid | null | 39000 | 2 |
from pyspark.sql import functions as F result = (employees .groupBy("dept") .agg( F.count("*").alias("people"), F.round(F.avg("salary")).alias("avg_salary"), F.max("salary").alias("top_salary"), ) .orderBy("dept"))
SELECT dept, COUNT(*) AS people, ROUND(AVG(salary)) AS avg_salary, MAX(salary) AS top_salary FROM employees GROUP BY dept ORDER BY dept
Farid's department is null, and he still gets a group: groupBy treats all nulls in a key as one group. In ascending order that null group sorts first.
Three ways to count
| Expression | Counts | With nulls |
|---|---|---|
F.count("*") / COUNT(*) | Rows in the group | Counted |
F.count("manager_id") | Non-null values of that column | Skipped |
F.countDistinct("dept") | Distinct non-null values | Skipped |
For a quick estimate on huge data, F.approx_count_distinct uses HyperLogLog++ and is far cheaper than an exact distinct count, with a default relative error of about 5%.
Filtering on an aggregate
SQL has HAVING for conditions on aggregates. In PySpark you just filter after the aggregation; CatalystCatalyst: Spark's query optimizer. It rewrites your DataFrame code into a faster equivalent plan before running it. Learn more → produces the same plan.
(employees.groupBy("dept") .agg(F.count("*").alias("n")) .filter(F.col("n") >= 2))
SELECT dept, COUNT(*) AS n FROM employees GROUP BY dept HAVING COUNT(*) >= 2
Under the hood: partial aggregation Optional deep dive
An aggregation needs all rows of a key on one executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more →, which means a shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more →. But Spark does not ship every row. It aggregates in two phases:
-
Map side
Each partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → computes partial results per key
-
Shuffle
Only one partial row per key per partition moves
-
Reduce side
Partials are merged into final results
For avg, the partial result is a (sum, count) pair; the final step divides. That is why the plan shows two HashAggregate nodes around an Exchange. With few distinct keys, this shuffles almost nothing.
collect_list cannot shrink their input in the map phase, so they shuffle every value. They are the aggregations to watch on big data.Common mistakes
- Selecting a column that is neither grouped nor aggregated — In SQL,
SELECT dept, name ... GROUP BY deptfails. In PySpark there is no way to express it: you must aggregatenamesomehow, for example withmax_byorcollect_list. - Using count(col) when you mean rows —
F.count("manager_id")skips the null manager and undercounts people. - Relying on output order — groupBy output order depends on hashing and partitioning. Always
orderBywhen order matters.
Key takeaways
groupBy(...).agg(...)returns one row per key combination.count("*")counts rows;count(col)skips nulls.- Filter after
aggto get SQL'sHAVING. - Spark aggregates before and after the shuffle, so most aggregations move little data.
Interview prep
THE QUESTION
"Why is avg cheap to distribute but median is not?"
percentile_approx, which merges compact sketches instead.Avoid: "median needs a sort". The real reason is that it cannot be computed from partial results, so it cannot be pre-aggregated per partition.
Follow-ups · answer out loud, then open
Follow-up"What is the difference between count('*'), count('col') and countDistinct('col')?"
count("*") counts rows. count("col") counts rows where col is not null. countDistinct counts distinct non-null values, and needs an extra aggregation step. approx_count_distinct is the cheap alternative for big data.Scenario"After a groupBy, you also need the name of each department from the same table. How?"
dept_id and dept_name, or use F.first("dept_name") / F.any_value. Do not group by the id and join back to the original table, which duplicates work.Trap"groupBy returns groups in key order."
Check yourself
3 questionsA group has 5 rows; 2 have a null bonus. What does F.count("bonus") return?
Show the answer
3. count(col) counts non-null values only. count("*") would return 5.
What is the PySpark equivalent of SQL HAVING?
Show the answer
A filter after agg. Filter on the aggregated column after agg. Catalyst treats it exactly like HAVING.
Why does the physical plan of an aggregation show two HashAggregate nodes?
Show the answer
Partial aggregation before the shuffle, final aggregation after. Spark pre-aggregates on each partition so only partial results are shuffled, then merges them.
Practise this
Problems that use groupBy + agg, graded on hidden tests
- Average Salary by DepartmentAggregations Easy
- Departments with Large TeamsAggregations Easy
- Find Repeat CustomersAggregations Easy
Keep going
Up next · Combine and summarise · lesson 2 of 4 · 5 min readdropDuplicates
Remove duplicate rows or keys, and why "keep the latest row" needs a window instead.
Related lessons
max_by / min_byPySpark functions · 4 min read
percentile_approxSpark internals · 6 min read
Narrow vs wide transformations
Previous: fillna / dropna
Primary sources: DataFrame.groupBy · GROUP BY clause