Skip to main content
PYSPARK • LESSON 140

Flattening Array Collections with explode()

How do we unnest an array of order items into individual rows, one row per item?

Advanced2 Minutes720 XP
🤔 THE QUESTION

How do we unnest an array of order items into individual rows, one row per item?

💡 WHAT IS IT?

explode(col) creates a new row for each element in the given array or map column.

🎯 WHAT IS IT USED FOR?

Unnesting shopping carts, normalising 1-to-many relationship payloads, and processing clickstream sequences.

💻 EXAMPLE
from pyspark.sql.functions import col, explode

exploded_df = df.select(col("order_id"), explode(col("items")).alias("item"))

🎯 Mission Objectives

Practice typing production-grade PySpark code for Flattening Array Collections with explode().

  • Import explode function
  • Unnest order items array into rows
  • Alias individual item records