Q:

How to get 5 records of column A based on column B in Spark DataFrame

I'm new to Spark and I have a Spark dataframe which returns below records. 
I want to sort data based on counts column in descending order and get top 5 of code column. 
counts = to_df.groupBy("id", "code").count().select("id", "code", sf.col("count").alias("counts"))  
sorting = counts.sort("code", ascending=False)
sorting.show()

I tried using filter and where and head.  But no luck.  I couldn't use 'where' without explicitly providing the value.  I want to make it dynamic. 
Data
+--------+-------+-+
| id|   code|counts|
+--------+-------+-+
| 1 |     ZB|     2|
| 2 |     ZB|     2|
| 3 |     ZB|     1|
| 4 |     ZB|     3|
| 5 |     ZB|     1|
| 6 |     ZB|     1|
| 7 |     ZB|     3|
| 8 |     XY|     3|
| 9 |     XY|     1|
| 10|     XY|     2|
| 11|     XY|     1|
| 12|     XY|     1|
| 13|     XY|     1|
| 14|     SD|     2|
| 15|     SD|     1|
| 16|     SD|     1|
| 17|     SD|     3|
| 18|     SD|     1|
| 19|     SD|     2|
| 1 |     SD|     7|
+--------+-------+-+

I want to get the output as below.  Could anyone please help. 
+--------+-------+-+
| id|   code|counts|
+--------+-------+-+
| 7 |     ZB|     3|
| 4 |     ZB|     3|
| 1 |     ZB|     2|
| 2 |     ZB|     2|
| 5 |     ZB|     1|
| 8 |     XY|     3|
| 10|     XY|     2|
| 11|     XY|     1|
| 12|     XY|     1|
| 13|     XY|     1|
| 1 |     SD|     7|
| 17|     SD|     3|
| 14|     SD|     2|
| 19|     SD|     2|
| 18|     SD|     1|
+--------+-------+-+

A:

PySpark Version using row_number() analytical function
from pyspark.sql import Window as W
from pyspark.sql import functions as F

w = W().partitionBy('code').orderBy('id')
df = df.withColumn("row_number", F.row_number().over(w))
df = df.filter(F.col('row_number') <= 5)
df = df.drop('row_number')
df.show()

+--------+-------+-+
| id|   code|counts|
+--------+-------+-+
| 7 |     ZB|     3|
| 4 |     ZB|     3|
| 1 |     ZB|     2|
| 2 |     ZB|     2|
| 5 |     ZB|     1|
| 8 |     XY|     3|
| 10|     XY|     2|
| 11|     XY|     1|
| 12|     XY|     1|
| 13|     XY|     1|
| 1 |     SD|     7|
| 17|     SD|     3|
| 14|     SD|     2|
| 19|     SD|     2|
| 18|     SD|     1|
+--------+-------+-+

