How do we filter for only the top 3 best-selling products in each merchandise category?
Ranking items with row_number() over category partitions, filtering for rank <= 3, and dropping rank.
Leaderboard generation, featured product recommendation carousels, and category digest reports.
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")Practice typing production-grade PySpark code for Top-N Records per Category with Window Filtering.