Skip to content
Bronze 4 min read · Aggregation 3 practice problems ↓

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

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

namedeptsalary
AshaEngineering72000
ChitraEngineering95000
BenSales48000
EshaSales50000
DevHR51000

Output

deptpeopleavg_salary
Engineering283500
Sales249000
HR151000
  1. 1
    Rows are split into groups by the key, here dept.
  2. 2
    Each aggregate is computed per group: count counts rows, avg averages non-nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → salaries.
  3. 3
    The output has one row per group. Output order is not guaranteed: add orderBy if you need one.

Run the example

PySparkSpark SQL

Input: employees

idnamedeptsalarymanager_id
1AshaEngineering72000null
2BenSales480001
3ChitraEngineering950001
4DevHR510001
5EshaSales500002
6Faridnull390002
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

ExpressionCountsWith nulls
F.count("*") / COUNT(*)Rows in the groupCounted
F.count("manager_id")Non-null values of that columnSkipped
F.countDistinct("dept")Distinct non-null valuesSkipped

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.

PySparkSpark SQL
(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:

  1. 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

  2. Shuffle

    Only one partial row per key per partition moves

  3. 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.

Why this matters: functions like 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 dept fails. In PySpark there is no way to express it: you must aggregate name somehow, for example with max_by or collect_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 orderBy when order matters.

Key takeaways

  • groupBy(...).agg(...) returns one row per key combination.
  • count("*") counts rows; count(col) skips nulls.
  • Filter after agg to get SQL's HAVING.
  • 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?"

avg decomposes into partial (sum, count) pairs that merge exactly, so each partition can pre-aggregate before the shuffle. An exact median needs all values of a group in one place. That is why Spark offers 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?"
If the name is functionally dependent on the key, group by both 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."
No. Output order after a shuffle is not defined. Add orderBy if the order matters.

Check yourself

3 questions

A 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

See all 36 problems →

Keep going

Up next · Combine and summarise · lesson 2 of 4 · 5 min read
dropDuplicates
Remove duplicate rows or keys, and why "keep the latest row" needs a window instead.

Related lessons

Previous: fillna / dropna

Primary sources: DataFrame.groupBy · GROUP BY clause