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

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

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

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

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

Syntax:

rank().over()

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

The syntax is as follows:

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

Apache Spark Official Documentation Link: rank()

Create a simple DataFrame

Let’s understand the use of the 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 continuously in PySpark Azure Databricks?

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

Example:

from pyspark.sql.functions import 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("rank", rank().over(window_spec)) \
.select("driver_name", "team", "points", "rank").show()

"""
Output:

+-----------+-------+------+----+
|driver_name|   team|points|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|   7|
|       Nick|McLaren|   2.0|   8|
+-----------+-------+------+----+

"""

As you can see, Nico and Kimi scored 5th rank, hence the rank was skipped to 7th for the next person.

How to rank records continuously based on specific groups in PySpark Azure Databricks?

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

Example:

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

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

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

"""
Output:

+-------+-----------+------+----+
|   team|driver_name|points|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.

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

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

Example:

from pyspark.sql.functions import rank, dense_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", "rank", "dense_rank").show()

"""
Output:

+-----------+-------+------+----+----------+
|driver_name|   team|points|rank|dense_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|   7|         6|
|       Nick|McLaren|   2.0|   8|         7|
+-----------+-------+------+----+----------+

"""

As you can see, Nico and Kimi scored the 5th rank, and the follow-up fellow receives the 6th rank. because the dense_rank() function leaves no gap between ranks.

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 rank() in Azure Databricks?

These could be the possible reasons:

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

Real World Use Case Scenarios for PySpark DataFrame rank() in 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 non-consecutive way. For example, Students C and D scored 98 marks out of 100 and you have to rank them as third. Now the student who scored 97 will be ranked as 5 instead of 4. This is a real-world example where the rank() function plays the main role.

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

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

  • dense_rank(): The difference between rank and dense_rank is that dense_rank leaves no 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 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.