Skip to main content
PYSPARK โ€ข LESSON 209

Higher-Order aggregate() on Arrays

How can we calculate the sum or product of all elements inside an array column without explode()?

Advancedโฑ 3 Minutesโญ 880 XP
๐Ÿค” THE QUESTION

How can we calculate the sum or product of all elements inside an array column without explode()?

๐Ÿ’ก WHAT IS IT?

The aggregate() higher-order function reduces an array to a scalar value using an accumulator and lambda functions.

๐ŸŽฏ WHAT IS IT USED FOR?

Calculating row-level totals from embedded line items in document-oriented pipelines.

๐Ÿ’ป EXAMPLE
df_total = df.withColumn("items_total", aggregate(col("item_prices"), lit(0.0), lambda acc, x: acc + x))

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Higher-Order aggregate() on Arrays.

  • โœ“ aggregate() higher-order function
  • โœ“ Accumulator initialization
  • โœ“ Row-level array reduction