Flatten arrays in PySpark with explode and arrays_zip
Use explode to turn each array element into a row. If two arrays describe matching items, combine them with arrays_zip before exploding so their positions stay aligned.
The snippets below use this local session. The complete downloadable scripts include setup, imports and result checks.
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.master("local[2]").appName("Recipe").getOrCreate()When working interactively, call spark.stop() after the final example.
Turn one array into rows
John and Mary each have two favourite fruits. Sam's list is empty and Alex's list is null. These last two records let us check whether flattening silently removes people we still need.
people = spark.sql("""
SELECT 'John' AS name, array('apple', 'banana') AS fruits
UNION ALL SELECT 'Mary', array('orange', 'grape')
UNION ALL SELECT 'Sam', CAST(array() AS ARRAY<STRING>)
UNION ALL SELECT 'Alex', CAST(NULL AS ARRAY<STRING>)
""")
flat = people.select("name", F.explode("fruits").alias("fruit"))
flat.orderBy("name", "fruit").show()
The result has four rows: apple and banana for John, orange and grape for Mary. The original name is repeated for each fruit. The array is replaced by the single fruit value selected for that row.
Keep people with no array elements
Ordinary explode contributes no rows for an empty or null array. Use explode_outer when those parent records must survive:
retained = people.select("name", F.explode_outer("fruits").alias("fruit"))
There are now six rows. Sam and Alex each have a row whose fruit is null. If you need to distinguish a null array from an empty array later, retain the original array or add a status column before flattening.
Flatten two arrays together
Suppose the numbers [1, 2, 3] correspond to letters [a, b]. Exploding each array independently creates every combination: three numbers times two letters produces six rows. That doesn't preserve the intended pairs.
pairs = spark.sql("SELECT array(1, 2, 3) AS numbers, array('a', 'b') AS letters")
paired = pairs.select(F.explode(F.arrays_zip("numbers", "letters")).alias("pair"))
result = paired.select("pair.numbers", "pair.letters").orderBy("numbers")
result.show()
numbers letters
1 a
2 b
3 NULL
arrays_zip makes an array of structs. Each struct contains values from the same position, and explode turns those structs into rows. The shorter array is padded with null, which is why number 3 has no letter. Check array lengths before this step if unequal lengths should be rejected.
A null input array is a different case from a short array. Choose whether it means missing data, an empty collection, or an invalid record before pairing. This example tests unequal lengths; it doesn't silently replace null inputs with empty arrays.
Verify row counts as well as values
The download checks four ordinary rows, six outer rows, and exactly three aligned pairs. These checks catch accidental row multiplication. After flattening real data, compare counts and inspect a few parent IDs before joining the result to another table.
To group values back into arrays, you can use collect_list, but don't assume it restores the original element order. Preserve an element position when order matters. Continue with the left-join tutorial when you need to enrich the flattened rows.
Run the complete example
Download the free examples ZIP and extract it. The code was checked with Python 3.13, Java 21 and PySpark 4.2.0. Use the installation guide if you need Java or Python first. From the extracted folder, run these PowerShell commands:
py -3.13 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe flatten_arrays.pyOn Linux or macOS, create the environment with python3 -m venv .venv and use .venv/bin/python for the install and run commands. Each script starts a local Spark session, checks the results and stops the session when finished.
Read the complete code on GitHub. Reference: Apache Spark 4.2 documentation.