Skip to main content

array_intersect

Returns a new array containing the intersection of elements in col1 and col2, without duplicates.

Syntax

Python
from pyspark.sql import functions as sf

sf.array_intersect(col1, col2)

Parameters

Parameter

Type

Description

col1

pyspark.sql.Column or str

Name of column containing the first array.

col2

pyspark.sql.Column or str

Name of column containing the second array.

Parameter

Type

Description

col1

pyspark.sql.Column or str

Name of column containing the first array.

col2

pyspark.sql.Column or str

Name of column containing the second array.

Returns

pyspark.sql.Column: A new array containing the intersection of elements in col1 and col2.

Examples

Example 1: Basic usage

Python
from pyspark.sql import Row, functions as sf
df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2=["c", "d", "a", "f"])])
df.select(sf.sort_array(sf.array_intersect(df.c1, df.c2))).show()
Output
+-----------------------------------------+
|sort_array(array_intersect(c1, c2), true)|
+-----------------------------------------+
| [a, c]|
+-----------------------------------------+

Example 2: Intersection with no common elements

Python
from pyspark.sql import Row, functions as sf
df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2=["d", "e", "f"])])
df.select(sf.array_intersect(df.c1, df.c2)).show()
Output
+-----------------------+
|array_intersect(c1, c2)|
+-----------------------+
| []|
+-----------------------+

Example 3: Intersection with all common elements

Python
from pyspark.sql import Row, functions as sf
df = spark.createDataFrame([Row(c1=["a", "b", "c"], c2=["a", "b", "c"])])
df.select(sf.sort_array(sf.array_intersect(df.c1, df.c2))).show()
Output
+-----------------------------------------+
|sort_array(array_intersect(c1, c2), true)|
+-----------------------------------------+
| [a, b, c]|
+-----------------------------------------+

Example 4: Intersection with null values

Python
from pyspark.sql import Row, functions as sf
df = spark.createDataFrame([Row(c1=["a", "b", None], c2=["a", None, "c"])])
df.select(sf.sort_array(sf.array_intersect(df.c1, df.c2))).show()
Output
+-----------------------------------------+
|sort_array(array_intersect(c1, c2), true)|
+-----------------------------------------+
| [NULL, a]|
+-----------------------------------------+

Example 5: Intersection with empty arrays

Python
from pyspark.sql import Row, functions as sf
from pyspark.sql.types import ArrayType, StringType, StructField, StructType
data = [Row(c1=[], c2=["a", "b", "c"])]
schema = StructType([
StructField("c1", ArrayType(StringType()), True),
StructField("c2", ArrayType(StringType()), True)
])
df = spark.createDataFrame(data, schema)
df.select(sf.array_intersect(df.c1, df.c2)).show()
Output
+-----------------------+
|array_intersect(c1, c2)|
+-----------------------+
| []|
+-----------------------+