Are you looking to find out how to collect the entire column into a list with duplicates of PySpark DataFrame using Azure Databricks cloud or maybe you are looking for a solution, to collect column data by grouping in PySpark Databricks using the collect_list() 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 collect_list() 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 collect_list() function in PySpark.
In this blog, I will teach you the following with practical examples:
- Syntax of collect_list() function
- Collect column values with duplication
- Using collect_list() as an aggregation function
The Pyspark collect_list() function is used to return a list of objects with duplicates.
Syntax:
collect_list()
Contents
- 1 What is the syntax of the collect_list() function in PySpark Azure Databricks?
- 2 Create a simple DataFrame
- 3 How to collect column values in PySpark Azure Databricks?
- 4 How to use the collect_list() function as an aggregation function in PySpark Azure Databricks?
- 5 When should you use the PySpark collect_list() in Azure Databricks?
- 6 Real World Use Case Scenarios for PySpark DataFrame collect_list() in Azure Databricks?
- 7 What are the alternatives to the collect_list() function in PySpark Azure Databricks?
- 8 Final Thoughts
What is the syntax of the collect_list() function in PySpark Azure Databricks?
The syntax is as follows:
collect_list(column)
Parameter Name | Required | Description |
column (str, Column) | Yes | It represents the column value to be collected together. |
Apache Spark Official Documentation Link: collect_list()
Create a simple DataFrame
Let’s understand the use of the collect_list() function with various 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,"Humberto","Human Resources",500),
(2,"Nada","Engineering",500),
(3,"Letta","Support",700),
(4,"Garry","Engineering",500),
(5,"Jeanne","Support",600)
]
columns = ["id","name","dept","salary"]
df = spark.createDataFrame(data, schema=columns)
df.printSchema()
df.show(truncate=False)
"""
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
|-- dept: string (nullable = true)
|-- salary: long (nullable = true)
+---+--------+---------------+------+
|id |name |dept |salary|
+---+--------+---------------+------+
|1 |Humberto|Human Resources|null |
|2 |Nada |Engineering |500 |
|3 |Letta |Support |700 |
|4 |Garry |Engineering |500 |
|5 |Jeanne |Support |600 |
+---+--------+---------------+------+
"""
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("header", True).load(file_path)
df_2.printSchema()
"""
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
|-- dept: string (nullable = true)
|-- salary: long (nullable = true)
"""
Note: Here, I will be using the manually created DataFrame.
How to collect column values in PySpark Azure Databricks?
In this example, let’s see how to use the collect_list() function in different ways to collect column values with duplication in PySpark Azure Databricks.
Example:
In this example, let’s try to collect the “salary” column values with duplication. Also, we have a null value. Let’s write a code and see the result.
from pyspark.sql.functions import collect_list
df.select(collect_list("salary").alias("salaries")).show(truncate=False)
"""
Output:
+--------------------+
|salaries |
+--------------------+
|[500, 700, 500, 600]|
+--------------------+
"""
You can see that we have all the values including the duplication value but no null values. The collect_list() function omits the null values.
How to use the collect_list() function as an aggregation function in PySpark Azure Databricks?
In this example, let’s see how to use the collect_list() function as an aggregation function in PySpark Azure Databricks.
Example:
In this example, let’s try to collect the “salary” column values by department wise with duplication. Also, we have a null value. Let’s write a code and see the result.
from pyspark.sql.functions import collect_list
df.groupBy("dept").agg(collect_list("salary").alias("salaries")).show(truncate=False)
"""
Output:
+---------------+----------+
|dept |salaries |
+---------------+----------+
|Human Resources|[] |
|Engineering |[500, 500]|
|Support |[700, 600]|
+---------------+----------+
"""
You can see that we have all the values grouped by the department including the duplication value but no null values. The collect_list() function omits the null values.
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 PySpark collect_list() in Azure Databricks?
When you want to get all records into a list, you can use the PySpark collect_list() function. This function returns unique records in a non-deterministic manner after shuffling.
Real World Use Case Scenarios for PySpark DataFrame collect_list() in Azure Databricks?
Let’s assume you have a student dataset across different states. For example Students A and B are from “Tamil Nadu” and “Kerala” and Students C and D are from “Mumbai”. You want to fetch records into a list [“Tamil Nadu”, “Kerala”, “Mumbai”, “Mumbai”]. You can use the PySpark collect_list() function to achieve the above-mentioned requirement.
What are the alternatives to the collect_list() function in PySpark Azure Databricks?
There are alternatives to the collect_list() function, which are as follows:
- collect_set(): used for getting records into a single list without any duplication.
Final Thoughts
In this article, we have learned about the PySpark collect_list() 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.
- 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.