Are you looking to find out how to check a value is present inside an array column of PySpark DataFrame using Azure Databricks cloud or maybe you are looking for a solution, to filter out columns based on a value in an array column in PySpark Databricks using the array_contains() 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 array_contains() 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 array_contains() function in PySpark.
In this blog, I will teach you the following with practical examples:
- Syntax of array_contains()
- Check value present in a column or not
- Filter out column using array_contains() as condition
The Pyspark array_contains() function is used to check whether a value is present in an array column or not. The function return True if the values is present, return False if the value is not present and null if the column values is null.
Syntax:
array_contains()
Contents
- 1 What is the syntax of the array_contains() function in PySpark Azure Databricks?
- 2 Create a simple DataFrame
- 3 How to check value is present in a column in PySpark Azure Databricks?
- 4 How to filter records using array_contains() in PySpark Azure Databricks?
- 5 When should you use the PySpark array_contains() in Azure Databricks?
- 6 Real World Use Case Scenarios for PySpark DataFrame array_contains() in Azure Databricks?
- 7 What are the alternatives to the array_contains() function in PySpark Azure Databricks?
- 8 Final Thoughts
What is the syntax of the array_contains() function in PySpark Azure Databricks?
The syntax is as follows:
array_contains(array_column, value)
Parameter Name | Required | Description |
column (str, Column) | Yes | It represents a column of ArrayType. |
value (str) | Yes | It represents the value to check if it is in the array column |
Apache Spark Official Documentation Link: array_contains()
Create a simple DataFrame
Let’s understand the use of the explode() 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
from pyspark.sql.types import StructType, StructField, ArrayType, StringType
data = [
("Anand",["Java", "Python"]),
("Berne",["Python", "Scala"]),
("Charan",["Java Script", "PHP"]),
("Denish",["Python", "SQL"]),
("Eren",None)
]
columns = ["full_name","languages"]
df = spark.createDataFrame(data, schema=columns)
df.printSchema()
df.show(truncate=False)
"""
root
|-- full_name: string (nullable = true)
|-- languages: array (nullable = true)
| |-- element: string (containsNull = true)
+---------+------------------+
|full_name|languages |
+---------+------------------+
|Anand |[Java, Python] |
|Berne |[Python, Scala] |
|Charan |[Java Script, PHP]|
|Denish |[Python, SQL] |
|Eren |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("json").load(file_path)
df_2.printSchema()
"""
root
root
|-- full_name: string (nullable = true)
|-- languages: array (nullable = true)
| |-- element: string (containsNull = true)
"""
Note: Here, I will be using the manually created DataFrame.
How to check value is present in a column in PySpark Azure Databricks?
The PySpark’s array_contains() function checks if the specified value is present in an array column or not. The following are the outputs of the array_contains() function:
- True – If the value is present.
- False – If the value is not present.
- null – If the array column is null/None.
Example 1:
In this example, let’s try to find out whether the students know Python or not.
# 1. Using select()
from pyspark.sql.functions import array_contains
df.select("*", array_contains("languages", "Python").alias("knowns_python")).show()
"""
Output:
+---------+------------------+-------------+
|full_name| languages|knowns_python|
+---------+------------------+-------------+
| Anand| [Java, Python]| true|
| Berne| [Python, Scala]| true|
| Charan|[Java Script, PHP]| false|
| Denish| [Python, SQL]| true|
| Eren| null| null|
+---------+------------------+-------------+
"""
As mentioned above, the person “Eren” record was null in the above example output.
Example 2:
In this example, let’s try to find out whether the students know Java or not.
# 2. Using withColumn()
from pyspark.sql.functions import array_contains
df.withColumn("knowns_java", array_contains("languages", "Java")).show()
"""
Output:
+---------+------------------+-----------+
|full_name| languages|knowns_java|
+---------+------------------+-----------+
| Anand| [Java, Python]| true|
| Berne| [Python, Scala]| false|
| Charan|[Java Script, PHP]| false|
| Denish| [Python, SQL]| false|
| Eren| null| null|
+---------+------------------+-----------+
"""
As mentioned above, the person “Eren” record was null in the above example output.
How to filter records using array_contains() in PySpark Azure Databricks?
In this example, let’s try to filter out students who know “Python” using array_contains() as a condition.
Examples:
from pyspark.sql.functions import array_contains
df.select("full_name", "languages") \
.filter(array_contains("languages", "Python")) \
.show()
"""
Output:
+---------+---------------+
|full_name| languages|
+---------+---------------+
| Anand| [Java, Python]|
| Berne|[Python, Scala]|
| Denish| [Python, SQL]|
+---------+---------------+
"""
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 array_contains() in Azure Databricks?
These could be the possible reasons:
- For checking an element inside an array or not
- To filter out records based on some element in an array
Real World Use Case Scenarios for PySpark DataFrame array_contains() in Azure Databricks?
Assume you were given a candidate’s dataset. The dataset contains candidate ID, name, and preferences for list type, for example (1, “Berne”, [“Chennai”, “Bangalore”, “Kochin”]). You can use the array_contains() function to filter out candidates who set preferences in “Chennai” by passing the array column and preferences into the defined function.
What are the alternatives to the array_contains() function in PySpark Azure Databricks?
There are multiple alternatives to the array_contains() function, which are as follows:
- Column.isin(): used for filtering out the records which present in an array
- You can also use PySpark SQL IN operator
Final Thoughts
In this article, we have learned about the PySpark array_contains() 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.