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?

Advanced3 Minutes880 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