I am monitoring a few hundred user activity online and trying to get average records posted for the last 5 rows (ignoring the missing dates in between). I am using Window.partitionBy to partition between users and rowsBetween to get the last 5 records but instead of giving me average of the last 5 records for each subsequent rows it seems to include all other rows into the average.
This is what I have tried:
from pyspark.sql import functions as f
from pyspark.sql.window import Window
win = Window.partitionBy('user_id').orderBy(f.col('record_date')).rowsBetween(-5, 0)
test = df.sort(
f.asc('record_date')
).withColumn(
'last5_avg', f.mean('total').over(win)
)
This is the result I get:
This is the result I want:

