Spark & PySpark
Window Functions & Ranking in PySpark — A Step-by-Step Guide with Real-World Use
In big data analytics, aggregations summarize — but window functions analyze in motion. They let you calculate running totals, ranks…
In big data analytics, aggregations summarize — but window functions analyze in motion.
They let you calculate running totals, ranks, moving averages, and comparisons — without collapsing your rows.
In short, window functions let you look around each row, not just at it.
Let’s break them down step-by-step with PySpark examples, visuals, and real-world use cases.
🚀 1. What Are Window Functions?
A window function performs a calculation across a set of rows related to the current row, called a window.
Every window function in Spark has three key components:

🧠 Analogy: Think of a spreadsheet — you can compute a running total down the rows, but the data itself remains intact. That’s what window functions do in Spark.
🧩 2. Creating the Spark Session
Let’s start with a small dataset.
from pyspark.sql import SparkSession
from pyspark.sql.window import Window
from pyspark.sql.functions import sum
spark = SparkSession.builder.appName("WindowFunctions").getOrCreate()
data = [
("North", "2025-01-01", 100),
("North", "2025-01-02", 200),
("North", "2025-01-03", 150),
("South", "2025-01-01", 300),
("South", "2025-01-02", 100)
]
df = spark.createDataFrame(data, ["region", "date", "sales"])
df.show()
⚡ 3. Running Total per Region
Let’s compute a running total of sales by region, ordered by date.
window_spec = Window.partitionBy("region").orderBy("date") \
.rowsBetween(Window.unboundedPreceding, 0)
df.withColumn("running_total", sum("sales").over(window_spec)).show()
Each region forms its own partition. Within each region, Spark calculates a cumulative total as it moves through the ordered dates — without collapsing rows.
💡 Why it matters:
Unlike groupBy, window functions retain all rows, making them perfect for trend analysis and dashboards.
🧮 4. Ranking Functions — rank(), dense_rank(), row_number()
Let’s explore Spark’s built-in ranking functions.
from pyspark.sql.functions import rank, dense_rank, row_number
window_spec = Window.partitionBy("region").orderBy(df["sales"].desc())
ranked_df = df.withColumn("rank", rank().over(window_spec)) \
.withColumn("dense_rank", dense_rank().over(window_spec)) \
.withColumn("row_number", row_number().over(window_spec))
ranked_df.show()

Spark assigns rank(), dense_rank(), and row_number() within each region partition based on descending sales order.
Unlike aggregations, window ranking functions preserve all rows — ideal for top-N queries and leaderboard-style analytics.
If there are ties:
rank()skips numbers (e.g., 1, 1, 3)dense_rank()doesn’t skip (e.g., 1, 1, 2)row_number()simply counts rows sequentially
🧠 Pro tip:
Use rank() when you care about position, dense_rank() for grouped equality, and row_number() for deduplication.
🧩 5. Use Case 1 — Top-N Customers by Spend
Here’s how to get top 3 spenders per region.
from pyspark.sql.functions import col
window_spec = Window.partitionBy("region").orderBy(col("sales").desc())
top_customers = df.withColumn("rank", rank().over(window_spec)) \
.filter(col("rank") <= 3)
top_customers.show()
Let us visualize flow of code to get top 3 spenders per region

💡 Common real-world use:
- Top-N products per category
- Most active users per month
- Best-performing ads per region
⚙️ 6. Use Case 2 — Moving Average
Now let’s calculate a 3-day moving average for each region.
from pyspark.sql.functions import avg
window_spec = Window.partitionBy("region").orderBy("date") \
.rowsBetween(-2, 0)
df.withColumn("moving_avg", avg("sales").over(window_spec)).show()
🧠 The moving window slides over 3 rows (-2, 0) — giving rolling averages for smooth trendlines.
💼 7. Real-World Example — Daily Revenue Dashboard
Let’s simulate a daily revenue summary that shows both:
- The cumulative revenue (
running_total) - The rank of each day by sales volume
window_region = Window.partitionBy("region").orderBy("date")
window_rank = Window.partitionBy("region").orderBy(df["sales"].desc())
df.withColumn("running_total", sum("sales").over(window_region)) \
.withColumn("rank_by_sales", rank().over(window_rank)) \
.show()

Raw Daily Sales → Window Partition (region) → Running Total + Rank → Dashboard View💡 This mirrors real dashboards — daily KPIs, user engagement ranks, or sales leaderboards.
🧠 8. Window Optimization Tips
Working with large datasets means every shuffle or recomputation matters.
Here are some key optimization techniques to make your PySpark window operations faster and more efficient.

🧩 Example: Optimizing Window Operations in PySpark
Below is a quick example showing how to use caching and repartitioning effectively when applying window functions on large data.
from pyspark.sql import SparkSession
from pyspark.sql.window import Window
from pyspark.sql.functions import sum, col
spark = SparkSession.builder.appName("OptimizedWindowExample").getOrCreate()
# Sample Data
data = [
("North", "2025-01-01", 100),
("North", "2025-01-02", 200),
("South", "2025-01-01", 300),
("South", "2025-01-02", 150),
]
df = spark.createDataFrame(data, ["region", "date", "sales"])
# Define window
window_spec = Window.partitionBy("region").orderBy("date") \
.rowsBetween(Window.unboundedPreceding, 0)
# ✅ Optimization Steps
# 1. Repartition by region for balanced workload
df = df.repartition("region")
# 2. Cache the DataFrame to avoid recomputation in multiple actions
df.cache()
# 3. Compute running total efficiently
optimized_df = df.withColumn("running_total", sum(col("sales")).over(window_spec))
optimized_df.show()
💡 Why this matters:
repartition("region")ensures even data distribution across executors, reducing skew.cache()avoids recomputing the same DataFrame when multiple window operations are applied (like cumulative totals + ranks).- Combined, they help maintain speed and scalability when working with millions of records.
🚨 9. Common Pitfalls (and Fixes)

🧾 10. Quick Reference — Window Function Cheat Sheet

🔚 11. Conclusion
Window functions are among PySpark’s most powerful tools.
They help you analyze change, order, and context — not just totals.
✅ Key Takeaways:
- Window ≠ groupBy — it retains all rows.
- Use partitioning + ordering wisely.
- Perfect for top-N, cumulative trends, and analytics dashboards.
💬 Window functions don’t summarize — they enrich your data.
🚀 12. Bonus — Try It Yourself
Run all examples interactively in this👉🔗 Google Colab Notebook
Tweak data, partitions, and frames — see the transformations in action.
🔥 13. Next in the Series
Up next:
“File Formats in Spark: CSV vs Parquet vs ORC vs Avro”
💬 14. Final Words
If this helped you master Spark window functions, you’re one step closer to thinking like a data engineer — analyzing not just “what happened,” but how it evolved.
Follow TheDataForge for weekly Spark deep dives & real-world engineering guides.
Let’s make big data simple — one Spark concept at a time. ⚡