How to use dense_rank() function in PySpark Azure Databricks?

Are you looking to find out how to rank records without gaps in PySpark DataFrame using Azure Databricks cloud or maybe you are looking for a solution, to rank records based on grouped records without gaps in PySpark Databricks using the row_number() 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 dense_rank() 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 use the dense_rank() function in PySpark.

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

  • Syntax of dense_rank() functions
  • Rank records without gaps
  • Rank records based on groups without gaps
  • Difference between dense rank and rank

The PySpark function dense_rank() is a window function used to rank of rows within a window partition without any gaps in Azure Databricks.

Syntax:

dense_rank().over()

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

The syntax is as follows:

dense_rank().over(window_spec)
Parameter NameRequiredDescription
window_spec(WindowSpec)YesIt represents the windowing column.
Table 1: dense_rank() Method in PySpark Databricks Parameter list with Details

Apache Spark Official Documentation Link: dense_rank()

Create a simple DataFrame

Let’s understand the use of the dense_rank() 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 = [
    ("Lewis","McLaren",10.0),
    ("Nick","McLaren",2.0),
    ("Nico","McLaren",6.0),
    ("Fernando","McLaren",3.0),
    ("Heikki","McLaren",8.0),
    ("Kazuki","Ferrari",9.0),
    ("Sébastien","Ferrari",7.0),
    ("Kimi","Ferrari",6.0)
]

df = spark.createDataFrame(data, schema=["driver_name","team","points"])
df.printSchema()
df.show(truncate=False)

"""
root
 |-- driver_name: string (nullable = true)
 |-- team: string (nullable = true)
 |-- points: double (nullable = true)

+-----------+-------+------+
|driver_name|team   |points|
+-----------+-------+------+
|Lewis      |McLaren|10.0  |
|Nick       |McLaren|2.0   |
|Nico       |McLaren|6.0   |
|Fernando   |McLaren|3.0   |
|Heikki     |McLaren|8.0   |
|Kazuki     |Ferrari|9.0   |
|Sébastien  |Ferrari|7.0   |
|Kimi       |Ferrari|6.0   |
+-----------+-------+------+
"""

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
 |-- driver_name: string (nullable = true)
 |-- team: string (nullable = true)
 |-- points: double (nullable = true)
"""

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

How to rank records without gaps in PySpark DataFrame using Azure Databricks?

Let’s see how to rank records based on columns descending without any gaps in PySpark DataFrame in Azure Databricks using various methods.

Example:

from pyspark.sql.functions import dense_rank, col
from pyspark.sql.window import Window

window_spec = Window.orderBy(col("points").desc())
# The window orderBy() -> acts as on which order the row has be numbered

df \
.withColumn("dense_rank", dense_rank().over(window_spec)) \
.select("driver_name", "team", "points", "dense_rank").show()

"""
Output:

+-----------+-------+------+----------+
|driver_name|   team|points|dense_rank|
+-----------+-------+------+----------+
|      Lewis|McLaren|  10.0|         1|
|     Kazuki|Ferrari|   9.0|         2|
|     Heikki|McLaren|   8.0|         3|
|  Sébastien|Ferrari|   7.0|         4|
|       Nico|McLaren|   6.0|         5|
|       Kimi|Ferrari|   6.0|         5|
|   Fernando|McLaren|   3.0|         6|
|       Nick|McLaren|   2.0|         7|
+-----------+-------+------+----------+

"""

As you can see, Nico and Kimi scored the 5th rank, and the follow-up driver scored the 6th.

How to rank records based on specific groups without gaps in PySpark DataFrame using Azure Databricks?

Let’s see how to rank records based on specific groups descending without any gaps in a PySpark DataFrame in Azure Databricks using various methods.

Example:

from pyspark.sql.window import Window
from pyspark.sql.functions import dense_rank

window_spec = Window.partitionBy("team").orderBy(col("points").desc())
# The window partitionBy() -> acts as groupBy

df\
.withColumn("dense_rank", dense_rank().over(window_spec))\
.select("team", "driver_name", "points", "dense_rank").show()

"""
Output:

+-------+-----------+------+----------+
|   team|driver_name|points|dense_rank|
+-------+-----------+------+----------+
|Ferrari|     Kazuki|   9.0|         1|
|Ferrari|  Sébastien|   7.0|         2|
|Ferrari|       Kimi|   6.0|         3|
|McLaren|      Lewis|  10.0|         1|
|McLaren|     Heikki|   8.0|         2|
|McLaren|       Nico|   6.0|         3|
|McLaren|   Fernando|   3.0|         4|
|McLaren|       Nick|   2.0|         5|
+-------+-----------+------+----------+

"""

As you can see, each driver of the team got ranked based on high ranks without gaps.

What’s the difference between dense_rank() and rank() functions of PySpark DataFrame using Azure Databricks?

Let’s see what the difference is between the dense_rank() and rank() functions of a PySpark DataFrame in Azure Databricks using an example.

Example:

from pyspark.sql.functions import dense_rank, rank, col
from pyspark.sql.window import Window

window_spec = Window.orderBy(col("points").desc())

df \
.withColumn("rank", rank().over(window_spec)) \
.withColumn("dense_rank", dense_rank().over(window_spec)) \
.select("driver_name", "team", "points", "dense_rank", "rank").show()

"""
Output:

+-----------+-------+------+----------+----+
|driver_name|   team|points|dense_rank|rank|
+-----------+-------+------+----------+----+
|      Lewis|McLaren|  10.0|         1|   1|
|     Kazuki|Ferrari|   9.0|         2|   2|
|     Heikki|McLaren|   8.0|         3|   3|
|  Sébastien|Ferrari|   7.0|         4|   4|
|       Nico|McLaren|   6.0|         5|   5|
|       Kimi|Ferrari|   6.0|         5|   5|
|   Fernando|McLaren|   3.0|         6|   7|
|       Nick|McLaren|   2.0|         7|   8|
+-----------+-------+------+----------+----+

"""

As you can see, Nico and Kimi scored the 5th rank, and the follow-up fellow receives the 6th rank. Because rank leaves a gap between ranks when they are tied.

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 use the dense_rank() in PySpark Azure Databricks?

These could be the possible reasons:

  1. When you want to rank records
  2. Rank records in a consecutive method

Real World Use Case Scenarios for dense rank in PySpark Azure Databricks?

Assume that you have a result dataset and you need to rank each student according to the marks they have scored but in a consecutive way. For example, Students C and D scored 98 marks out of 100 and you have to rank both of them as the Third rank and use can use dense rank to rank them in the consecutive method.

What are the alternatives to the dense_rank() function in PySpark Azure Databricks?

There are multiple alternatives to the dense_rank() function, which are as follows:

  • rank(): The difference between rank and dense_rank is that rank leaves gaps in the ranking sequence when there are ties.
  • percent_rank(): used for finding the relativity rank of records.

Final Thoughts

In this article, we have learned about the PySpark dense_rank() method of DataFrame in 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.

Arud Seka Berne S

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.