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?

Production3 Minutes1800 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