How do we compute purchase recency deltas, cumulative lifetime spend, and customer spending ranks simultaneously?
Advanced multi-window pipeline computing lag() date deltas, cumulative running totals, and global spending ranks.
Customer 360 feature stores, VIP loyalty tiering, and high-value customer segmentation.
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))Practice typing production-grade PySpark code for Customer 360 Analytics & Rolling Window Metrics.