QuestionQ5

VerifiedDeveloping Code for Data Processing using Python and SQL

A data engineer is analyzing transactional data in a PySpark DataFrame df that contains customer_id, transaction_timestamp (precise to milliseconds), and amount_spent. The goal is to calculate a cumulative sum of amount_spent for each customer, strictly ordered by transaction_timestamp. The cumulative sum must include every transaction from the earliest timestamp through and including the current row, while preserving temporal order within each customer partition.

Which PySpark code snippet most accurately defines the required window specification and applies the aggregation to produce the correct cumulative expenditure per customer?

Explanation

A per-customer running total requires partitionBy("customer_id") to isolate customers, orderBy("transaction_timestamp") to establish chronological order, and rowsBetween(Window.unboundedPreceding, Window.currentRow) to include each ordered row from the start of that customer’s partition through the current row. PySpark documents rowsBetween as an inclusive row-based frame and shows this unbounded-preceding-to-current-row pattern for ordered window calculations. PySpark Window documentation

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!