Sub topic 14
Window functions
This chapter assumes you can create a DataFrame in a Databricks notebook, use groupBy and agg, and read basic PySpark column expressions. It uses the orders DataFrame from earlier chapters, with columns order_id, customer, order_date and amount.
What a window function does
groupBy collapses many rows into one row per group. A window function computes a value over a related set of rows, called a window, and keeps every input row. Use one when you need a running total, a rank, or a comparison with the previous row.
A window has three parts:
- Partition: the rows are split into groups, such as one group per customer.
- Order: the rows inside each partition are sorted, such as by date.
- Frame: the slice of ordered rows the function sees for the current row.
Running total
from pyspark.sql import functions as F
from pyspark.sql import Window
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
).withColumn("order_date", F.to_date("order_date"))
w = Window.partitionBy("customer").orderBy("order_date")
running = orders.withColumn("running_total", F.sum("amount").over(w))
display(running)F.sum("amount").over(w) applies the aggregate to the window. Alice's rows get 120.0 and then 150.0. Carol's amount is null, and sum skips nulls, so her running total is null because no non-null value has been seen yet.
When a window has an orderBy and no explicit frame, the default frame runs from the first row of the partition to the current row. This is why the total grows row by row.
Ranking and previous values
Ranking functions and lag need an ordered window. Spark raises an error if there is no orderBy.
w = Window.partitionBy("customer").orderBy("order_date")
ranked = (
orders
.withColumn("order_number", F.row_number().over(w))
.withColumn("previous_amount", F.lag("amount", 1).over(w))
.withColumn("change", F.col("amount") - F.col("previous_amount"))
)
display(ranked)row_number()numbers rows 1, 2, 3 within each partition, with no ties.rank()gives tied rows the same number and leaves gaps after them.dense_rank()leaves no gaps.lag(col, n)returns the value fromnrows earlier. The first row of a partition gets null.leadlooks forward instead.
A common pattern is to keep each customer's latest order. Number the rows in descending date order, then filter:
latest_w = Window.partitionBy("customer").orderBy(F.col("order_date").desc())
latest = (
orders
.withColumn("rn", F.row_number().over(latest_w))
.filter(F.col("rn") == 1)
.drop("rn")
)
display(latest)Choosing the frame
You can set the frame yourself with rowsBetween. This one averages the current row and the one before it:
w2 = (
Window.partitionBy("customer")
.orderBy("order_date")
.rowsBetween(-1, Window.currentRow)
)
moving = orders.withColumn("avg_last_two", F.avg("amount").over(w2))
display(moving)Window.unboundedPreceding and Window.unboundedFollowing mark the ends of the partition.
Common errors
- No partition:
Window.orderBy(...)alone puts all rows in one partition. Spark moves all the data to a single task, which is slow and can run out of memory on large tables. - Missing order:
row_number,rankandlagfail withoutorderBy. - Ties in the order column: if two rows share an
order_date,row_numberpicks between them arbitrarily. Add a tie-breaker such asorder_idto theorderBy. - Filtering on a window column: you cannot use a window expression inside
filterdirectly. Create the column withwithColumnfirst, as in thernexample.
Each window with a different partition and order causes a shuffle, which is a redistribution of rows across the cluster. Reuse one Window specification where you can.
Exercise
Write window code that adds a column customer_rank ranking each customer's orders from largest to smallest amount, and explain why row_number might be a worse choice than rank if two orders have the same amount.
Show answer
Use w = Window.partitionBy("customer").orderBy(F.col("amount").desc()) and orders.withColumn("customer_rank", F.rank().over(w)). With equal amounts, row_number still gives the rows different numbers, and which row gets the lower number is arbitrary. rank gives both rows the same number, which better reflects the tie.