library(tidyverse)
library(readxl)
input = read_excel("Power Query/PQ_Challenge_146.xlsx", range = "A1:D14")
test = read_excel("Power Query/PQ_Challenge_146.xlsx", range = "F1:I7")
result = input %>%
group_by(Group) %>%
mutate(Category = ifelse(Value == Threshold, "Equal",
ifelse(Value > Threshold, "High", "Low"))) %>%
ungroup() %>%
filter(Category != "Equal") %>%
group_by(Group, Category) %>%
mutate(valid = ifelse(Category == "High", min(Value), max(Value))) %>%
ungroup() %>%
filter(Value == valid) %>%
select(-valid, -Category)
identical(result, test)
# [1] TRUEExcel BI - PowerQuery Challenge 146
excel-challenges
power-query
Group For a group -

Challenge Description
Group For a 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_146.xlsx", usecols="A:D", nrows=14)
test = pd.read_excel("PQ_Challenge_146.xlsx", usecols="F:I", nrows=7)
result = input_data.copy()
result["Category"] = result.apply(
lambda r: "Equal" if r["Value"] == r["Threshold"] else ("High" if r["Value"] > r["Threshold"] else "Low"),
axis=1,
)
result = result[result["Category"] != "Equal"].copy()
result["valid"] = result.groupby(["Group", "Category"])["Value"].transform("min")
low_mask = result["Category"] == "Low"
result.loc[low_mask, "valid"] = result.loc[low_mask].groupby(["Group", "Category"])["Value"].transform("max")
result = result[result["Value"] == result["valid"]].drop(columns=["valid", "Category"]).reset_index(drop=True)
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.