library(tidyverse)
library(slider)
library(readxl)
input = read_excel("Power Query/PQ_Challenge_141.xlsx", range = "A1:C35")
test = read_excel("Power Query/PQ_Challenge_141.xlsx", range = "E1:I35")
result = input %>%
group_by(Month) %>%
mutate(
`3 Year MV` = slide_dbl(Defects, mean, .after = -1, .before = 3, .complete = TRUE) %>% round(0),
`5 Year MV` = slide_dbl(Defects, mean, .after = -1, .before = 5, .complete = TRUE) %>% round(0)
) %>%
ungroup()
identical(result, test)
#> [1] TRUEExcel BI - PowerQuery Challenge 141
excel-challenges
power-query
& 5 year moving averages for each month group.

Challenge Description
& 5 year moving averages for each month group.
Solutions
Logic:
Reads the workbook range needed for the challenge
Aggregates or ranks values at the relevant grouping level
Builds helper columns that drive the final output
Strengths:
- The R solution stays close to the workbook logic and keeps the transformation compact.
Areas for Improvement:
- The code assumes the workbook layout and selected ranges remain stable.
Gem:
- The best part of the solution is choosing the right intermediate shape before formatting the final output.
import pandas as pd
input_data = pd.read_excel("PQ_Challenge_141.xlsx", usecols="A:C", nrows=35)
test = pd.read_excel("PQ_Challenge_141.xlsx", usecols="E:I", nrows=35)
result = input_data.copy()
result["3 Year MV"] = (
result.groupby("Month")["Defects"]
.transform(lambda s: s.rolling(window=4, min_periods=4).mean().round(0).shift(-1))
)
result["5 Year MV"] = (
result.groupby("Month")["Defects"]
.transform(lambda s: s.rolling(window=6, min_periods=6).mean().round(0).shift(-1))
)
print(result.equals(test))Logic:
Reads the workbook range needed for the challenge
Aggregates or ranks values at the relevant grouping level
Strengths:
- The Python version follows the same workbook rule in a direct pandas-oriented implementation.
Areas for Improvement:
- As with the R version, any workbook layout change would require small adjustments.
Gem:
- The implementation stays close to the source challenge instead of adding unnecessary abstraction.
Difficulty Level
This task is moderate:
It combines reshaping, grouping, or parsing steps that are common in Power Query style problems.
The main challenge is reproducing the workbook output structure exactly.