Skip to main content
PYSPARK โ€ข LESSON 111

Fetching Prior Row Values with lag()

How do we look back to fetch the previous order amount for each customer to compute spending changes?

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

How do we look back to fetch the previous order amount for each customer to compute spending changes?

๐Ÿ’ก WHAT IS IT?

lag(col, offset).over(windowSpec) retrieves the value of a column from offset rows prior to the current row.

๐ŸŽฏ WHAT IS IT USED FOR?

Calculating period-over-period growth, session duration, and customer spending deltas.

๐Ÿ’ป EXAMPLE
from pyspark.sql.window import Window
from pyspark.sql.functions import col, lag

window_spec = Window.partitionBy("customer_id").orderBy("order_date")
df = df.withColumn("prev_order_amount", lag(col("amount"), 1).over(window_spec))

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Fetching Prior Row Values with lag().

  • โœ“ Import lag function
  • โœ“ Retrieve prior order amount with offset 1
  • โœ“ Enable order-over-order comparative analytics