library(tidyverse)
library(readxl)
path = "Power Query/PQ_Challenge_196.xlsx"
input = read_xlsx(path, range = "A1:C11")
test = read_xlsx(path, range = "F1:O5")
result = input %>%
mutate(class1 = Class) %>%
pivot_wider(names_from = Subject, values_from = c(class1, Marks), names_sep = "-") %>%
select(-Class) %>%
rename_with(~str_remove(., "class1-"), starts_with("class1-")) %>%
select(sort(names(.), decreasing = FALSE)) %>%
select(1:3,9:10, everything())
identical(result, test)
#> [1] TRUEExcel BI - PowerQuery Challenge 196
excel-challenges
power-query
Transpose the problem table into result table. Class will be populated under subjects and marks will be populated under headers Marks-Subject Name.

Challenge Description
Transpose the problem table into result table. Class will be populated under subjects and marks will be populated under headers Marks-Subject Name.
Solutions
Logic:
Reshapes the data into the structure required by the result table
Builds helper columns that drive the final output
Uses direct pattern parsing where the workbook encodes logic in text
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
path = "PQ_Challenge_196.xlsx"
input = pd.read_excel(path, usecols="A:C", nrows=11)
test = pd.read_excel(path, usecols="F:O", nrows=4)
result = input.copy()
result["class1"] = result["Class"]
result = result.pivot_table(index=["class1"], columns=["Subject"], values=["class1", "Marks"], aggfunc="first", fill_value="")
result.columns = result.columns.map(lambda x: "-".join(x))
result = result.reset_index()
result = result.sort_index(axis=1)
result.columns = result.columns.str.replace("Class-", "")
result = result.drop(columns=["class1"])
result = result.applymap(lambda x: pd.to_numeric(x, errors="coerce", downcast="integer"))
test = test.applymap(lambda x: pd.to_numeric(x, errors="coerce", downcast="integer"))
print(result.equals(test)) # TrueLogic:
Reads the workbook range needed for the challenge
Reshapes the data into the structure required by the result table
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.