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?

Advanced2 Minutes740 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