🎬No video for this question yet. The written answer is below.
Write Pyspark code to get running total
📝 Answer
Interviewer:
Can you write PySpark code to calculate a running total? Also explain how it works in a real-time scenario.
Candidate:
So basically, when I hear running total, I immediately think about window functions in Spark.
Let me explain how I approach this step by step.
First, I understand the requirement. Running total means cumulative sum based on a certain order, like date or transaction sequence.
In my project, I had a use case where I needed to calculate cumulative sales for each customer over time.
So the key idea is… we need to define a window partition and an order.
Partition defines the group, like customer_id, and order defines the sequence, like transaction_date.
Then we use a window function with sum.
Let me show the code.
from pyspark.sql import SparkSession
from pyspark.sql.window import Window
from pyspark.sql.functions import sum
spark = SparkSession.builder.getOrCreate()
# Sample Data
data = [
(1, "2024-01-01", 100),
(1, "2024-01-02", 200),
(1, "2024-01-03", 300),
(2, "2024-01-01", 150),
(2, "2024-01-02", 250)
]
columns = ["customer_id", "date", "amount"]
df = spark.createDataFrame(data, columns)
# Define Window
window_spec = Window.partitionBy("customer_id") \
.orderBy("date") \
.rowsBetween(Window.unboundedPreceding, Window.currentRow)
# Running Total
df = df.withColumn("running_total", sum("amount").over(window_spec))
df.show()
So basically, what is happening here is…
First, we partition data by customer_id. That means each customer’s data is processed separately.
Then we order the data by date, so we know the sequence.
Then rowsBetween defines the range from the first row to the current row.
So for each row, Spark calculates the sum of all previous rows plus the current row.
In my real-time project, this was used for cumulative revenue tracking.
One important thing I learned is that window functions can be expensive if not used properly, especially with large datasets.
So I always ensure proper partitioning and avoid unnecessary wide transformations.
So in simple terms… running total in PySpark is achieved using window functions with partitioning and ordering.
Interviewer (Follow-up):
Good. What happens if you don’t define orderBy in the window function for running total?