How to count unique values in PySpark Azure Databricks?

Are you looking to find out how to get unique values count of PySpark DataFrame using Azure Databricks cloud or maybe you are looking for a solution, to find the distinct values excluding null values of PySpark Databricks using the count_distinct() function? If you are looking for any of these problem solutions, you have landed on the correct page. I will also help you how to use PySpark countDistinct() function with multiple examples in Azure Databricks. I will explain it by taking a practical example. So please don’t waste time let’s start with a step-by-step guide to understand how to finding unique values count in PySpark.

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

  • Syntax of count_distinct() function
  • Count single-column distinct value
  • Count multiple columns distinct value
  • Count the unique values using distinct() method

The Pyspark count_distinct() function is used to count the unique values of single or multiple columns of PySpark DataFrame.

Syntax:

count_distinct()

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

The syntax is as follows:

count_distinct(*columns)
Parameter NameRequiredDescription
columns (str, Column)YesIt represents the column to be considered for a distinct count.
Table 1: count_distinct() Method in PySpark Databricks Parameter list with Details

Apache Spark Official Documentation Link: count_distinct()

Create a simple DataFrame

Let’s understand the use of the count_distinct() function with a variety of examples. Let’s start by creating a 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,"1000","Pontiac"),
    (2,"Ram Van B350",None),
    (3,"SRX","Cadillac"),
    (4,None,None),
    (5,"CLK-Class",None),
    (6,"GLC",None),
    (7,"Jetta",None),
    (8,None,None),
    (9,"3500 Club Coupe",None),
    (10,"Tacoma",None)
]

columns = ["id","model","make"]
df = spark.createDataFrame(data, schema=columns)
df.printSchema()
df.show(truncate=False)

"""
root
 |-- id: long (nullable = true)
 |-- model: string (nullable = true)
 |-- make: string (nullable = true)

+---+---------------+--------+
|id |model          |make    |
+---+---------------+--------+
|1  |1000           |Pontiac |
|2  |Ram Van B350   |null    |
|3  |SRX            |Cadillac|
|4  |null           |null    |
|5  |CLK-Class      |null    |
|6  |GLC            |null    |
|7  |Jetta          |null    |
|8  |null           |null    |
|9  |3500 Club Coupe|null    |
|10 |Tacoma         |null    |
+---+---------------+--------+
"""

b) Creating a DataFrame by reading files

Download and use the below source file.

# replace the file_path with the source file location which you have downloaded.

df_2 = spark.read.format("csv").option("inferSchema", True).option("header", True).load(file_path)
df_2.printSchema()

"""
root
 |-- id: long (nullable = true)
 |-- model: string (nullable = true)
 |-- make: string (nullable = true)
"""

Note: Here, I will be using the manually created DataFrame.

How to count single column unique values in PySpark Azure Databricks?

Let’s see how to count single-column unique or distinct values of PySpark DataFrame in Azure Databricks using various methods.

Example:

from pyspark.sql.functions import count_distinct

df.select(count_distinct("model")).show()

"""
Output:

+---------------------+
|count(DISTINCT model)|
+---------------------+
|                    8|
+---------------------+

"""

How to count multiple columns unique values in PySpark Azure Databricks?

Let’s see how to count multiple columns’ unique or distinct values of PySpark DataFrame in Azure Databricks using various methods.

Example:

from pyspark.sql.functions import count_distinct

df.select(count_distinct("model", "make")).show()

"""
Output:

+---------------------------+
|count(DISTINCT model, make)|
+---------------------------+
|                          2|
+---------------------------+

"""

Note: When you pass multiple columns into the count_distinct() function, it will always return the smaller distinct value.

How to get unique counts in PySpark Azure Databricks?

Let’s see how to use the distinct() function and get the unique counts of PySpark DataFrame in Azure Databricks using various methods.

Example:

df.select("make").distinct().show()
df.select("make").distinct().count()

"""
Output:

+--------+
|    make|
+--------+
| Pontiac|
|    null|
|Cadillac|
+--------+

3

"""

In the above, you can see that the distinct function fetches all the unique values including null. Hence, this generated three records. But the countDistinct() function will not consider null values.

I have attached the complete code used in this blog in a notebook format to this GitHub link. You can download and import this notebook in databricks, jupyter notebook, etc.

When should you use the PySpark count_distinct() in Azure Databricks?

The PySpark count_distinct() function could be used, when you want to find out the count of the unique values.

Real World Use Case Scenarios for counting distinct values in PySpark Azure Databricks?

Assume that you were given a large dataset of people’s information including their state and you where asked to find out the number of unique states listed in te DataFrame. In this scenario the PySpark count_distinct() function helps in finding out the unique values count.

What are the alternatives for counting unique values in PySpark Azure Databricks?

There are multiple alternatives for counting unique values, which are as follows:

  • count_distinct(): used for finding the count of the unique values
  • countDistinct(): used for finding the count of the unique values, an alias of count_distinct()
  • distinct().count(): You can chain distinct() and count() to achieve the above behavior

Final Thoughts

In this article, we have learned about finding the unique values count 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.