Excel BI - PowerQuery Challenge 222

excel-challenges
power-query
Student Test1 Test2 Test3 Test4 Marks1
Published

March 24, 2026

Illustration for Excel BI - PowerQuery Challenge 222

Challenge Description

Student Test1 Test2 Test3 Test4 Marks1

Solutions

library(tidyverse)
library(readxl)

path = "Power Query/PQ_Challenge_222.xlsx"
input = read_excel(path, range = "A1:I7")
test  = read_excel(path, range = "A11:D17")

result = input %>%
  pivot_longer(cols = -c(1), names_to = c(".value", "Type"), names_pattern = "(\\D+)(\\d+)") %>%
  mutate(rank = rank(desc(Marks), ties.method = "first"), .by = Test) %>%
  select(-Type) %>%
  unite("TM", Student, Marks, sep = " ") %>%
  pivot_wider(names_from = rank, values_from = TM, names_prefix = "Student")  %>%
  select(Subjects = Test, sort(names(.)[-1])) %>%
  filter(!is.na(Subjects)) %>%
  mutate(across(2:ncol(.), ~ifelse(as.numeric(str_extract(., "\\d+")) >= 40, str_remove(., "\\s\\d+"), NA_character_))) %>%
  select(where(~!all(is.na(.)))) %>%
  arrange(Subjects) 

identical(result, test)
#> [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

    • 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
import numpy as np

path = "PQ_Challenge_222.xlsx"
input = pd.read_excel(path, usecols="A:I", nrows=7)
test = pd.read_excel(path, usecols="A:D", skiprows=10, nrows=7)

input_long = input.melt(id_vars='Student', var_name='variable', value_name='Marks')

first_part = input_long[input_long['variable'].str.contains('Test')]
second_part = input_long[input_long['variable'].str.contains('Marks')].reset_index(drop=True).add_suffix('_2')

output = pd.concat([first_part, second_part], axis=1).drop(columns=['variable', 'variable_2', 'Student_2'])
output = output.rename(columns={'Marks': 'Subjects', 'Marks_2': 'Marks'}).dropna()
output['Marks'] = pd.to_numeric(output['Marks'], errors='coerce')
output['Rank'] = output.groupby('Subjects')['Marks'].rank(ascending=False, method='first').astype(int)
output = output.sort_values(['Subjects', 'Rank']).reset_index(drop=True)
output['Student'] = output['Student'] + ' ' + output['Marks'].astype(str)
output = output.drop(columns='Marks')

output = output.pivot(index='Subjects', columns='Rank', values='Student').reset_index()
output.columns = ['Subjects'] + [f'Student{i}' for i in range(1, len(output.columns))]

for col in output.columns[1:]:
    output[col] = np.where(output[col].notnull() & (output[col].str.split().str[-1].astype(float) >= 40),
                           output[col].str.split().str[:-1].str.join(' '), 
                           np.nan)

output = output.dropna(axis=1, how='all')

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

    • Reads the workbook range needed for the challenge

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

    • Aggregates or ranks values at the relevant grouping level

    • Applies the rule iteratively until the output is complete

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