Skip to main content
PYSPARK โ€ข LESSON 197

Customer 360 Analytics & Rolling Window Metrics

How do we compute purchase recency deltas, cumulative lifetime spend, and customer spending ranks simultaneously?

Productionโฑ 3 Minutesโญ 1800 XP
๐Ÿค” THE QUESTION

How do we compute purchase recency deltas, cumulative lifetime spend, and customer spending ranks simultaneously?

๐Ÿ’ก WHAT IS IT?

Advanced multi-window pipeline computing lag() date deltas, cumulative running totals, and global spending ranks.

๐ŸŽฏ WHAT IS IT USED FOR?

Customer 360 feature stores, VIP loyalty tiering, and high-value customer segmentation.

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

cust_order_window = Window.partitionBy("customer_id").orderBy("order_date")
running_spend_window = Window.partitionBy("customer_id").orderBy("order_date").rowsBetween(Window.unboundedPreceding, Window.currentRow)
rank_window = Window.orderBy(col("lifetime_spend").desc())

customer_360 = transactions \
    .withColumn("days_since_prev_order", (col("order_date") - lag("order_date", 1).over(cust_order_window)).cast("int")) \
    .withColumn("lifetime_spend", sum("amount").over(running_spend_window)) \
    .withColumn("customer_rank", rank().over(rank_window))

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Customer 360 Analytics & Rolling Window Metrics.

  • โœ“ Apply multiple analytical Window specifications
  • โœ“ Compute order recency with lag()
  • โœ“ Calculate cumulative lifetime spend and global rank