Skip to main content
PYSPARK โ€ข LESSON 141

Preserving Empty Rows with explode_outer()

How do we unnest an array while retaining users who have zero or null elements in their list?

Advancedโฑ 2 Minutesโญ 740 XP
๐Ÿค” THE QUESTION

How do we unnest an array while retaining users who have zero or null elements in their list?

๐Ÿ’ก WHAT IS IT?

explode_outer() unnests arrays like explode(), but outputs a row with NULL instead of dropping empty arrays.

๐ŸŽฏ WHAT IS IT USED FOR?

Preventing accidental row loss when flattening optional array attributes like user subscriptions.

๐Ÿ’ป EXAMPLE
from pyspark.sql.functions import col, explode_outer

df = df.select(col("user_id"), explode_outer(col("subscriptions")).alias("subscription"))

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Preserving Empty Rows with explode_outer().

  • โœ“ Import explode_outer function
  • โœ“ Flatten array while preserving empty records
  • โœ“ Retain users with zero subscriptions