How to perform groupBy distinct count in PySpark Azure Databricks?

Are you looking to find how to perform groupBy distinct count in PySpark Dataframe using Azure Databricks cloud or maybe you are looking for a solution, to count unique 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 distinct count in PySpark Azure Databricks.

In this blog, I will teach you the following with practical examples:

  • Syntax of groupBy()
  • Count Distinct using count_distinct() function
  • Count Distinct using groupBy() and count() functions
  • Count Distinct using SQL expression

groupBy() method is used to collect records of Dataframe together based on column identical values specified in PySpark Azure Databricks.

Syntax: dataframe_name.groupBy()

What is the syntax of the groupBy() function in PySpark Azure Databricks?

The syntax is as follows:

dataframe_name.groupBy(*cols)
Parameter NameRequiredDescription
*cols (str, list or Column)YesIt represents the columns to be considered for grouping.
Table 1: groupBy() Method in PySpark Databricks Parameter list with Details

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 = [ 
    (1,"Reuben","Delhi","Infosys"),
    (2,"Aldrich","Kerala","CTS"),
    (3,"Ede","Tamil Nadu","CTS"),
    (4,"Benjamin","Tamil Nadu","Infosys"),
    (5,"Adler","Mumbai","Infosys"),
    (6,"Jolynn","Mumbai","CTS"),
    (7,"Daile","Kerala","TCS"),
    (8,"Cullin","Mumbai","TCS"),
    (9,"Yul","Tamil Nadu","TCS"),
    (10,"Valaree","Mumbai","Infosys")
]

df = spark.createDataFrame(data, schema=["id","name","state","company"])
df.printSchema()
df.show(truncate=False)

"""
root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- state: string (nullable = true)
 |-- company: string (nullable = true)

+---+--------+----------+-------+
|id |name    |state     |company|
+---+--------+----------+-------+
|1  |Reuben  |Delhi     |Infosys|
|2  |Aldrich |Kerala    |CTS    |
|3  |Ede     |Tamil Nadu|CTS    |
|4  |Benjamin|Tamil Nadu|Infosys|
|5  |Adler   |Mumbai    |Infosys|
|6  |Jolynn  |Mumbai    |CTS    |
|7  |Daile   |Kerala    |TCS    |
|8  |Cullin  |Mumbai    |TCS    |
|9  |Yul     |Tamil Nadu|TCS    |
|10 |Valaree |Mumbai    |Infosys|
+---+--------+----------+-------+
"""

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
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- state: string (nullable = true)
 |-- company: string (nullable = true)
"""

How to get number of unique records by grouping columns in PySpark using count_distinct() function?

In this section, let’s see how to get number of unique records by grouping columns in PySpark using the count_distinct() function with some practical examples.

Examples:

from pyspark.sql.functions import count_distinct, countDistinct

# Method 1:
df.groupBy("company").agg(count_distinct("state").alias("distinct_count")).show()

# Method 2:
df.groupBy("company").agg(countDistinct("state").alias("distinct_count")).show()

# The above codes generate the following output

"""
Output:

+-------+--------------+
|company|distinct_count|
+-------+--------------+
|Infosys|             3|
|    TCS|             3|
|    CTS|             3|
+-------+--------------+

"""

Note: The count_distinct() returns a new Column for a distinct count. The countDistinct() function is an alias for count_distinct() and it is encouraged to use count_distinct() function directly.

How to get number of unique records using groupBy() and count() functions in PySpark?

In this section, let’s see how to get number of unique records using groupBy() and count() functions in PySpark with a practical example.

Example:

df \
.groupBy("company", "state").count() \
.groupBy("company").count().show()

"""
Output:

+-------+-----+
|company|count|
+-------+-----+
|Infosys|    3|
|    TCS|    3|
|    CTS|    3|
+-------+-----+

"""

How to get number of unique records by grouping columns in PySpark Azure Databricks using SQL expression?

In this section, let’s see how to get unique 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.

Example:

df.createOrReplaceTempView("employees")

spark.sql('''
    SELECT company, COUNT(DISTINCT state) AS distinct_conut
    FROM employees
    GROUP BY company
''').show()

"""
Output:

+-------+--------------+
|company|distinct_conut|
+-------+--------------+
|Infosys|             3|
|    TCS|             3|
|    CTS|             3|
+-------+--------------+

"""

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 unique records by grouping columns in PySpark Azure Databricks?

These could be the possible reasons:

  • The group by distinct count method is a common transformation that we generally use in PySpark Azure Databricks used for fetching the unique record count in a particular group.
  • Whenever you don’t want to count similar records in a group.

Real World Use Case Scenarios for counting unique 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 each company’s work location count. In this case, the groupby distinct count practice helps in finding the requirement.

What are the alternatives for counting unique records by grouping columns in PySpark Azure Databricks?

There are multiple alternatives for counting unique records by grouping columns in PySpark Azure Databricks, which are as follows:

  1. Use groupBy() function followed by count() function
  2. Using PySpark SQL function

Final Thoughts

In this article, we have learned about counting unique 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.

PySpark in Azure Databricks, as explained by Arud Seka Berne S on azurelib.com.

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.