Skip to main content
PYSPARK โ€ข LESSON 70

Conditional NULL Handling with when()

How do we conditionally replace null category values with 'Uncategorized' while preserving valid strings?

Intermediateโฑ 2 Minutesโญ 370 XP
๐Ÿค” THE QUESTION

How do we conditionally replace null category values with 'Uncategorized' while preserving valid strings?

๐Ÿ’ก WHAT IS IT?

Combining when(col.isNull(), ...) with otherwise(col) to standardize missing category fields.

๐ŸŽฏ WHAT IS IT USED FOR?

Product catalog classification, taxonomy standardization, and reporting dimension cleansing.

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

df = df.withColumn(
    "normalized_category",
    when(col("category").isNull(), "Uncategorized")
    .otherwise(col("category"))
)

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Conditional NULL Handling with when().

  • โœ“ Check isNull() within when() condition
  • โœ“ Assign fallback string literal
  • โœ“ Preserve existing valid categories