The customer retention division wants to track purchase trends. Calculate the difference in transaction amounts compared to the previous purchase for each customer.
The processing pipeline will ingest the following local mock file structures (e.g. simulated as `dataset.csv`):
| purchase_id | customer_id | date | amount |
|---|---|---|---|
| 1 | 101 | 2026-07-01 | 150.0 |
| 2 | 101 | 2026-07-02 | 180.0 |
| 3 | 102 | 2026-07-01 | 200.0 |
| 4 | 101 | 2026-07-03 | 160.0 |
| 5 | 102 | 2026-07-04 | 220.0 |
purchase_id,customer_id,date,amount 1,101,2026-07-01,150.0 2,101,2026-07-02,180.0 3,102,2026-07-01,200.0 4,101,2026-07-03,160.0 5,102,2026-07-04,220.0
Copy this starter template to write the data transformation logic:
# starter.py - Customer Purchase Trends
from pyspark.sql import SparkSession
from pyspark.sql.window import Window
from pyspark.sql.functions import col, lag
def calculate_trends():
spark = SparkSession.builder.appName("PurchaseTrends").getOrCreate()
# TODO: Read dataset.csv, configure lag window spec, find price diffs
pass
if __name__ == "__main__":
calculate_trends()customer_id and sorted chronologically by date.
prev_amount column using lag(col("amount"), 1).over(windowSpec) to fetch the previous row's amount.
amount_diff by subtracting prev_amount from the current amount. Select reporting fields and print output.