Skip to main content
PYSPARK โ€ข LESSON 239

Year-over-Year Growth with lag(12)

How can we calculate year-over-year revenue growth percentages across monthly time series data?

Advancedโฑ 3 Minutesโญ 880 XP
๐Ÿค” THE QUESTION

How can we calculate year-over-year revenue growth percentages across monthly time series data?

๐Ÿ’ก WHAT IS IT?

lag('monthly_revenue', 12) retrieves the exact revenue from the corresponding month in the previous year.

๐ŸŽฏ WHAT IS IT USED FOR?

Financial reporting, executive dashboards, and macroeconomic trend tracking.

๐Ÿ’ป EXAMPLE
w = Window.partitionBy("business_unit").orderBy("month_id")
df_yoy = df.withColumn("prev_year_revenue", lag("monthly_revenue", 12).over(w)).withColumn("yoy_growth_pct", ((col("monthly_revenue") - col("prev_year_revenue")) / col("prev_year_revenue")) * 100)

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Year-over-Year Growth with lag(12).

  • โœ“ lag(12) 12-period offset
  • โœ“ Year-over-year growth calculation
  • โœ“ Financial time series analytics