What are window functions in PySpark and how do you use them? Show a running total and the latest order per customer.
Source: PySpark documentation
A window function computes a value for each row from a related group of rows without collapsing them. Define Window.partitionBy(key).orderBy(col), then apply row_number(), lag() or an aggregate with a frame, such as rowsBetween(Window.unboundedPreceding, Window.currentRow) for a running total.
What a window function does
A groupBy collapses rows into one per group. A window function keeps every row and adds a value computed from a window of related rows. A window spec has three parts:
partitionBy(...): the group (for example, customer).orderBy(...): the order inside the group.- an optional frame: which rows around the current row are included.
from pyspark.sql import Window, functions as F
w = Window.partitionBy("customer_id").orderBy(F.col("order_ts").desc())
latest = (orders
.withColumn("rn", F.row_number().over(w))
.filter("rn = 1")
.drop("rn")) # latest order per customer
Other tools: rank(), dense_rank(), lag("amount", 1), lead(...), sum("amount").over(w).
The default frame gotcha
When you add orderBy, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Rows with the same ordering value (ties) are treated as one group, so they all get the same running total. Without orderBy the frame is the whole partition.
Example data with a tie on day 2:
| day | amount | sum default (RANGE) | sum with rowsBetween(unboundedPreceding, currentRow) |
|---|---|---|---|
| 1 | 10 | 10 | 10 |
| 2 | 20 | 60 | 30 |
| 2 | 30 | 60 | 60 |
| 3 | 40 | 100 | 100 |
I checked these numbers with SQL window functions (same frame rules). For a true row-by-row running total, set the frame explicitly:
w_run = (Window.partitionBy("customer_id")
.orderBy("day", "order_id") # add a tiebreaker
.rowsBetween(Window.unboundedPreceding, Window.currentRow))
orders.withColumn("running_total", F.sum("amount").over(w_run))
Ranking functions on ties
| Function | Values for scores 100, 90, 90, 80 |
|---|---|
row_number() | 1, 2, 3, 4 |
rank() | 1, 2, 2, 4 |
dense_rank() | 1, 2, 2, 3 |
Use row_number() when you need exactly one row per group (latest order); add a tiebreaker column so the result is deterministic.
Performance
A window with partitionBy triggers a shuffle by that key and a sort inside each partition. A window without partitionBy moves all data into one partition and warns about performance, so avoid it on large data. A very skewed key makes one task slow.
- 1WindowpartitionBy(customer).orderBy(ts desc)
- 2row_number()numbers rows in each partition
- 3No collapseevery row kept
- 4Filterrow 1 = latest order per customer
See the concept: Spark shufflegroupBy moves every record to the partition that owns its key
Input partition 0
Input partition 1
Input partition 2
Stage 1: narrow transformations run in place
Key points
- A window function adds a computed column without collapsing rows.
- Spec =
partitionBy+orderBy+ optional frame. - With
orderBy, the default frame is RANGE UNBOUNDED PRECEDING to CURRENT ROW, so ties get the same running value. - Use
rowsBetweenplus a tiebreaker column for a row-by-row running total. row_number() = 1is the standard "latest row per key" pattern.
Common mistakes
- Expecting a running total to increase on every row when the order column has ties.
- Using a window without
partitionByon a large DataFrame. - Picking
rank()when exactly one row per group is needed. - Ordering by a non-unique column with
row_number()and getting non-deterministic results.
Prerequisites
- DataFrame groupBy
- Shuffle and partitions
Best practices
- Add a unique tiebreaker to
orderByfor deterministic results. - Set the frame explicitly for running aggregates.
- Filter early to reduce shuffled data, and watch skew on the partition key.
- Check
explain()for the Window node and the Exchange before it.
Likely follow-ups
- What is the difference between
rowsBetweenandrangeBetween? - What is the difference between
row_number,rankanddense_rank? - How would you compute a 7-day moving average with a window function?
- Why is a window without
partitionBya performance problem? - How would you get the second highest salary per department with a window?