Featured Article

Master PySpark Group By with Easy Example Code

Kenneth Jul 13, 2026

Spark is a powerful data processing engine that can handle large datasets with ease. One of its key operations is the ability to group data based on specific criteria, which can provide valuable insights into the data. In this guide, we'll explore how you can use PySpark's groupBy operation to group data and perform aggregations.

PySpark Groupby Explained with Example
PySpark Groupby Explained with Example

Let's begin with a simple example. Suppose we have a DataFrame containing user data, and we want to group users by their country of residence and find the total number of users in each country. We can achieve this using the Spark SQL API with PySpark.

pyspark mapreduce - Google Search Computer Coding, Google Search, Computer, Science, Coding
pyspark mapreduce - Google Search Computer Coding, Google Search, Computer, Science, Coding

Grouping DataFrame by a Single Column

In this section, we'll learn how to group data based on a single column and perform aggregations.

several people are holding puzzle pieces together
several people are holding puzzle pieces together

First, let's create a simple DataFrame and display its content:

```python from pyspark.sql import SparkSession spark = SparkSession.builder.appName('PySparkGroupByExample').getOrCreate() data = [(1, 'USA'), (2, 'USA'), (3, 'Canada'), (4, 'Canada'), (5, 'Mexico'), (6, 'Mexico')] df = spark.createDataFrame(data, ['id', 'country']) df.show() ```

Using groupBy and count

Know About Apache Spark Using PySpark for Data Engineering
Know About Apache Spark Using PySpark for Data Engineering

Now, let's group the DataFrame by the 'country' column and count the number of users in each country:

```python df.groupBy('country').count().show() ```

This will output:

``` +-------+-----+ | country|count| +-------+-----+ | Mexico| 3| | Canada| 2| | USA| 2| +-------+-----+ ```

Using agg and sum

a group of people standing on top of a hill with their arms in the air
a group of people standing on top of a hill with their arms in the air

Let's explore another example. Suppose we have a DataFrame with user ids, their ages, and the amount they spent. We want to find the total amount spent by users in each country:

```python data = [(1, 'USA', 25, 100), (2, 'USA', 30, 150), (3, 'Canada', 35, 50), (4, 'Canada', 28, 70), (5, 'Mexico', 40, 200), (6, 'Mexico', 45, 120)] df = spark.createDataFrame(data, ['id', 'country', 'age', 'amount']) df.show() ```

Now, let's group the DataFrame by the 'country' column and find the total amount spent in each country:

```python df.groupBy('country').agg({'amount': 'sum'}).show() ```

This will output:

Spark DataFrame – How to select the first row of each group?
Spark DataFrame – How to select the first row of each group?

``` +-------+-------+ | country|sum(amount)| +-------+-------+ | Mexico| 320| | Canada| 120| | USA| 250| +-------+-------+ ```

Grouping DataFrame by Multiple Columns

Sometimes, we may need to group data based on multiple columns. Let's see how we can do this.

Office staff work. business people planning strategy. effective teamwork. colleagues sit at table and communicate. corporate project discussion or negotiation. vector group of employees brainstorming | Premium Vector
Office staff work. business people planning strategy. effective teamwork. colleagues sit at table and communicate. corporate project discussion or negotiation. vector group of employees brainstorming | Premium Vector
a group of people standing in a circle with the word teamwork
a group of people standing in a circle with the word teamwork
a group of people standing next to each other
a group of people standing next to each other
The Benefits & Examples of Using Apache Spark with PySpark | Exxact Blog
The Benefits & Examples of Using Apache Spark with PySpark | Exxact Blog
a group of people standing on the side of a building with their thumbs up in front of them
a group of people standing on the side of a building with their thumbs up in front of them
PySpark Timestamp Difference (seconds, minutes, hours)
PySpark Timestamp Difference (seconds, minutes, hours)
Just vibes💗
Just vibes💗
a group of men sitting next to each other in front of a black background with words written on it
a group of men sitting next to each other in front of a black background with words written on it
a group of children sitting at desks in front of a projector screen
a group of children sitting at desks in front of a projector screen

Suppose we want to find the total amount spent by users in each country and age group:

Using groupBy and multiple columns

We can use the '*' operator to select all columns in our groupings. Let's group the DataFrame by 'country' and 'age' and find the total amount spent in each country-age group:

```python df.groupBy('country', 'age').agg({'amount': 'sum'}).show() ```

This will output:

``` +-------+---+-------+---------+ | country|age|sum(amount)| +-------+---+-------+---------+ | Mexico| 40| 320| | Mexico| 45| 120| | Canada| 28| 70| | Canada| 35| 50| | USA| 25| 100| | USA| 30| 150| +-------+---+-------+---------+ ```

And that's how you can use PySpark's groupBy operation to group data. Whether you're working with a single column or multiple columns, PySpark provides flexible APIs to handle your grouping and aggregation needs. Happy data processing!