Excel BI - PowerQuery Challenge 228

excel-challenges
power-query
Unpivot the problem table into result table.
Published

March 24, 2026

Illustration for Excel BI - PowerQuery Challenge 228

Challenge Description

Unpivot the problem table into result table.

Solutions

library(tidyverse)
library(readxl)
library(unpivotr)

path = "Power Query/PQ_Challenge_228.xlsx"
input = read_excel(path, range = "A1:H5", col_names = F)
test  = read_excel(path, range = "J1:M20") %>%
  arrange(Category, Student, Value)

result = input %>%
  as_cells() %>%
  behead("left", "Student") %>%
  behead("up-left", "Category") %>%
  behead("up", "Value") %>%
  select(Student, Category, Value, Marks = chr) %>%
  mutate(Marks = as.integer(Marks)) %>%
  na.omit() %>%
  arrange(Category, Student, Value)

all.equal(result, test, check.attributes = F)
#> [1] TRUE
  • Logic:

    • Reads the workbook range needed for the challenge

    • Reshapes the data into the structure required by the result table

    • 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

path = "PQ_Challenge_228.xlsx"
input = pd.read_excel(path, header=None, usecols="A:H", nrows=5)
test = pd.read_excel(path, usecols="J:M", nrows=20).sort_values(by=['Category','Student', 'Value']).reset_index(drop=True)

t_input = input.T
t_input.columns = t_input.iloc[0]
t_input = t_input.drop(t_input.index[0]).reset_index(drop=True)
t_input.columns = ['Category', 'Value', 'X', 'Y', 'Z']
t_input['Category'] = t_input['Category'].ffill()
t_input = t_input.melt(id_vars=['Category', 'Value'], var_name='Student', value_name='Marks')
t_input = t_input[['Student', 'Category', 'Value', 'Marks']].dropna().sort_values(by=['Category','Student', 'Value']).reset_index(drop=True)
t_input['Marks'] = t_input['Marks'].astype("int64")

print(t_input.equals(test)) # True
  • Logic:

    • 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.