Are you looking to find how to perform groupBy count in PySpark Dataframe using Azure Databricks cloud or maybe you are looking for a solution, to count records by grouping identical records of a Dataframe in PySpark Databricks? If you are looking for any of these problem solutions, then you have landed on the correct page. I will also show you how to use both PySpark and Spark SQL to perform these actions in Azure Databricks. I will explain it by taking a practical example. So don’t waste time let’s start step by step guide to understanding how to perform groupBy count in PySpark Azure Databricks.
groupBy() method is used to collect records of Dataframe together based on column identical values specified in PySpark Azure Databricks.
Syntax: dataframe_name.groupBy()
Contents
- 1 What is the syntax of the groupBy() function in PySpark Azure Databricks?
- 2 Create a simple DataFrame
- 3 How to count number of records by grouping single column in PySpark using Azure Databricks?
- 4 How to count number of records by grouping multiple columns in PySpark using Azure Databricks?
- 5 How to count number of records by grouping columns in PySpark Azure Databricks using SQL expression?
- 6 When should you count records by grouping columns in PySpark Azure Databricks?
- 7 Real World Use Case Scenarios for counting records by grouping columns in PySpark Azure Databricks?
- 8 What are the alternatives for counting records by grouping columns in PySpark Azure Databricks?
- 9 Final Thoughts
What is the syntax of the groupBy() function in PySpark Azure Databricks?
The syntax is as follows:
dataframe_name.groupBy(*cols)
Parameter Name | Required | Description |
*cols (str, list or Column) | Yes | It represents the columns to be considered for grouping. |
Apache Spark Official documentation link: groupBy()
Create a simple DataFrame
Gentle reminder:
In Databricks,
- sparkSession made available as spark
- sparkContext made available as sc
In case, you want to create it manually, use the below code.
from pyspark.sql.session import SparkSession
spark = SparkSession.builder
.master("local[*]")
.appName("azurelib.com")
.getOrCreate()
sc = spark.sparkContext
a) Create manual PySpark DataFrame
data = [
("XC70","USA",2002),
("NV2500","Europe",2004),
("Savana 2500","USA",2002),
("Dakota","Europe",2002),
("LeSabre","Japan",2002),
("Cooper","Japan",2004),
("929","Europe",2004),
("Eldorado","Europe",2002),
("09-May","Japan",2002),
("Daewoo Kalos","USA",2004)
]
df = spark.createDataFrame(data, schema=["model","origin","release_year"])
df.printSchema()
df.show(truncate=False)
"""
root
|-- model: string (nullable = true)
|-- origin: string (nullable = true)
|-- release_year: long (nullable = true)
+------------+------+------------+
|model |origin|release_year|
+------------+------+------------+
|XC70 |USA |2002 |
|NV2500 |Europe|2004 |
|Savana 2500 |USA |2002 |
|Dakota |Europe|2002 |
|LeSabre |Japan |2002 |
|Cooper |Japan |2004 |
|929 |Europe|2004 |
|Eldorado |Europe|2002 |
|09-May |Japan |2002 |
|Daewoo Kalos|USA |2004 |
+------------+------+------------+
"""
b) Creating a DataFrame by reading files
Download and use the below source file.
# replace the file_paths with the source file location which you have downloaded.
df_2 = spark.read.format("csv").option("header", True).load(file_path)
df_2.printSchema()
"""
root
|-- model: string (nullable = true)
|-- origin: string (nullable = true)
|-- release_year: long (nullable = true)
"""
Note: Here, I will be using the manually created DataFrame.
How to count number of records by grouping single column in PySpark using Azure Databricks?
In this section, let’s see how to count records by grouping a single column in PySpark DataFrame using Azure Databricks with an example using an inner join.
Examples:
In the below example, we are trying to get the number of cars per region.
df.groupBy("origin").count().show()
"""
Output:
+------+-----+
|origin|count|
+------+-----+
| USA| 3|
|Europe| 4|
| Japan| 3|
+------+-----+
"""
How to count number of records by grouping multiple columns in PySpark using Azure Databricks?
In this section, let’s see how to count records by grouping multiple columns in PySpark DataFrame using Azure Databricks with an example using an inner join.
Examples:
In the below example, we are trying to get the number of cars per region each year.
df.groupBy("origin","release_year").count().show()
"""
Output:
+------+------------+-----+
|origin|release_year|count|
+------+------------+-----+
| USA| 2002| 2|
|Europe| 2004| 2|
|Europe| 2002| 2|
| Japan| 2002| 2|
| Japan| 2004| 1|
| USA| 2004| 1|
+------+------------+-----+
"""
How to count number of records by grouping columns in PySpark Azure Databricks using SQL expression?
In this section, let’s see how to count records by grouping columns in PySpark Azure Databricks using SQL expression with an example. In order to use a raw SQL expression, we have to convert our DataFrame into a SQL view.
df.createOrReplaceTempView("cars")
Example 1:
# 1. Single column
spark.sql('''
SELECT origin, count(1) AS count FROM cars
GROUP BY origin
''').show()
"""
Output:
+------+-----+
|origin|count|
+------+-----+
| USA| 3|
|Europe| 4|
| Japan| 3|
+------+-----+
"""
Example 2:
# 2. Multiple column
spark.sql('''
SELECT origin, count(1) AS count FROM cars
GROUP BY origin, release_year
''').show()
"""
Output:
+------+-----+
|origin|count|
+------+-----+
| USA| 2|
|Europe| 2|
|Europe| 2|
| Japan| 2|
| Japan| 1|
| USA| 1|
+------+-----+
"""
I have attached the complete code used in this blog in notebook format to this GitHub link. You can download and import this notebook in databricks, jupyter notebook, etc.
When should you count records by grouping columns in PySpark Azure Databricks?
These could be the possible reasons:
- The group by count method is a common transformation that we generally use in PySpark Azure Databricks used for fetching the record count in a particular group.
- Whenever you want to count records in a group.
Real World Use Case Scenarios for counting records by grouping columns in PySpark Azure Databricks?
Let’s assume, we have a large dataset of employees, their work location, and their company. The requirement may be to fetch the number of employees working in each company. In this case, the groupby count practice helps in finding the requirement.
What are the alternatives for counting records by grouping columns in PySpark Azure Databricks?
There are multiple alternatives for counting records by grouping columns in PySpark Azure Databricks, which are as follows:
- groupBy().count()
- groupBy().agg()
- Using PySpark SQL expression
Final Thoughts
In this article, we have learned about counting records by grouping single and multiple columns in PySpark Azure Databricks along with the examples explained clearly. I have also covered different scenarios with practical examples that could be possible. I hope the information that was provided helped in gaining knowledge.
Please share your comments and suggestions in the comment section below and I will try to answer all your queries as time permits.
- For Azure Study material Join Telegram group : Telegram group link:
- Azure Jobs and other updates Follow me on LinkedIn: Azure Updates on LinkedIn
- Azure Tutorial Videos: Videos Link
- Azure Databricks Lesson 1
- Azure Databricks Lesson 2
- Azure Databricks Lesson 3
- Azure Databricks Lesson 4
- Azure Databricks Lesson 5
- Azure Databricks Lesson 6
- Azure Databricks Lesson 7
As a big data engineer, I design and build scalable data processing systems and integrate them with various data sources and databases. I have a strong background in Python and am proficient in big data technologies such as Hadoop, Hive, Spark, Databricks, and Azure. My interest lies in working with large datasets and deriving actionable insights to support informed business decisions.