Get the top N rows per group in PySpark
To keep the two largest sales from each store, use a window partitioned by store, number the rows inside each partition, and filter that number. Decide how ties should behave before choosing the ranking function.
The snippets below use this local session. The complete downloadable scripts include setup, imports and result checks.
from pyspark.sql import SparkSession, Window, functions as F
spark = SparkSession.builder.master("local[2]").appName("Recipe").getOrCreate()When working interactively, call spark.stop() after the final example.
A small dataset with a deliberate tie
London has three sales: 100, 90 and 90. Bristol has 50, 40 and 30. Exactly two rows per store means one of London's tied sales must be left out. A unique sale ID gives us a repeatable way to choose it.
sales = spark.sql("""
SELECT * FROM VALUES
(1, 'London', 100), (2, 'London', 90), (3, 'London', 90),
(4, 'Bristol', 50), (5, 'Bristol', 40), (6, 'Bristol', 30)
AS sales(sale_id, store, amount)
""")
The SQL VALUES expression creates the demonstration DataFrame without a separate input file. You can use the same window with a DataFrame loaded from CSV or Parquet.
Number rows inside each store
order = Window.partitionBy("store").orderBy(
F.col("amount").desc(), F.col("sale_id").asc()
)
top_two = sales.withColumn("position", F.row_number().over(order)).filter(
F.col("position") <= 2
)
top_two.orderBy("store", "position").show()
partitionBy("store") restarts numbering for every store. Amount sorts descending; sale ID sorts ascending when amounts match. In this example, sale ID is unique. In your own data, use enough ordering columns to identify one row unambiguously.
For N rows, replace 2 in the filter with your positive integer N. A group with fewer than N rows simply returns all its rows. The final orderBy controls how we display the result; the window's ordering determines which rows qualify.
store sale_id amount position
Bristol 4 50 1
Bristol 5 40 2
London 1 100 1
London 2 90 2
Include all rows tied at the cutoff
If both 90-value London sales must be kept, rank by amount alone. Adding the unique ID here would break the tie and change that policy.
by_amount = Window.partitionBy("store").orderBy(F.col("amount").desc())
with_ties = sales.withColumn("rank", F.rank().over(by_amount)).filter(
F.col("rank") <= 2
)
This returns five sales: IDs 1, 2, 3, 4 and 5. row_number gives every row its own position. rank shares positions for equal values and leaves gaps after ties. dense_rank has no gaps, so filtering it selects the top N distinct values instead. Choose the function that matches the business question.
Check the result before using it downstream
The downloaded script asserts the expected sale IDs for both policies. Add ties to your own test data; an example with all different amounts can't show this distinction. Decide explicitly whether null amounts are eligible, and filter them first if they aren't.
For larger inputs, the window may move and sort data. Filter unwanted records and select needed columns before ranking. Keep collect() for tiny test results such as this one. Use the execution-plan tutorial to inspect the work.
Run the complete example
Download the free examples ZIP and extract it. The code was checked with Python 3.13, Java 21 and PySpark 4.2.0. Use the installation guide if you need Java or Python first. From the extracted folder, run these PowerShell commands:
py -3.13 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe top_n.pyOn Linux or macOS, create the environment with python3 -m venv .venv and use .venv/bin/python for the install and run commands. Each script starts a local Spark session, checks the results and stops the session when finished.
Read the complete code on GitHub. Reference: Apache Spark 4.2 documentation.