How would you implement a rolling window calculation in PySpark?

Instruction: Implement a rolling calculation on time-series data, specifying whether the window counts rows, elapsed time or calendar days and how missing dates and entities are handled.

Context: This question tests the candidate's ability to manipulate time-series data using window functions in PySpark, a common operation in data analysis and processing.

Updated

Choose whether the window means a number of records, elapsed time or calendar dates. rowsBetween(-6, 0) means up to seven rows. A bounded rangeBetween uses the numeric ordering value, not an implicit number of days.

For a daily calculation, normalize timestamps to the intended business date and aggregate to one row per entity/date first. This fixture assumes one non-null observation per entity/date and an existing SparkSession named spark:

from pyspark.sql import Window, functions as F

daily = spark.createDataFrame([
    ("A", "2026-01-01", 10.0), ("A", "2026-01-02", 20.0),
    ("A", "2026-01-08", 80.0), ("B", "2026-01-08", 100.0),
], "entity string, day string, value double")
daily = (daily.withColumn("day", F.to_date("day"))
         .withColumn("day_number", F.datediff("day", F.lit("1970-01-01"))))
assert not daily.filter("entity IS NULL OR day IS NULL OR value IS NULL").take(1)
assert not daily.groupBy("entity", "day").count().filter("count > 1").take(1)
window = (Window.partitionBy("entity").orderBy("day_number")
          .rangeBetween(-6, 0))
result = daily.withColumn("observed_day_mean", F.avg("value").over(window))
last_a = result.filter("entity = 'A' AND day = DATE '2026-01-08'").first()
assert last_a.observed_day_mean == 50.0
assert result.filter("entity = 'B'").first().observed_day_mean == 100.0

At January 8 the range includes January 2 through January 8, so the observed values are 20 and 80; January 1 is excluded. The mean is over observed non-null days, not seven filled calendar positions. If absent days should count as zero or require a complete window, construct a calendar grid and state that policy instead.

The window's own orderBy establishes its ordering; a preceding global sort is unnecessary. partitionBy prevents unrelated entities from mixing. For elapsed seconds, use a suitable numeric epoch value and explicit inclusive bounds; second precision and daylight-saving behavior differ from calendar days. Bounded ranges with peers include tied ordering values, while row windows need a deterministic tie-breaker. Numeric range-frame contract

Related Questions