Skip to main content
PYSPARK • LESSON 119

Top-N Records per Category with Window Filtering

How do we filter for only the top 3 best-selling products in each merchandise category?

Advanced3 Minutes720 XP
🤔 THE QUESTION

How do we filter for only the top 3 best-selling products in each merchandise category?

💡 WHAT IS IT?

Ranking items with row_number() over category partitions, filtering for rank <= 3, and dropping rank.

🎯 WHAT IS IT USED FOR?

Leaderboard generation, featured product recommendation carousels, and category digest reports.

💻 EXAMPLE
from pyspark.sql.window import Window
from pyspark.sql.functions import col, row_number

window_spec = Window.partitionBy("category").orderBy(col("sales").desc())
top3_df = df.withColumn("rank", row_number().over(window_spec)) \
            .filter(col("rank") <= 3) \
            .drop("rank")

🎯 Mission Objectives

Practice typing production-grade PySpark code for Top-N Records per Category with Window Filtering.

  • Rank products by sales per category
  • Filter top 3 items with boolean predicate
  • Cleanly drop temporary rank column