library(tidyverse)
library(readxl)
path = "Power Query/300-399/319/PQ_Challenge_319.xlsx"
input = read_excel(path, sheet = 2, range = "A1:I4")
test = read_excel(path, sheet = 2, range = "A9:F18")
result = input %>%
pivot_longer(-Fruits,
names_to = c("Q", ".value"),
names_sep = "-") %>%
mutate(Total = Price * Quantity) %>%
pivot_longer(-c(Fruits, Q),
names_to = "Quarters",
values_to = "Values") %>%
pivot_wider(names_from = Q,
values_from = Values) %>%
mutate(Fruits = ifelse(row_number() == 1, Fruits, NA_character_), .by = Fruits)
all.equal(result, test)
# > [1] TRUEExcel BI - PowerQuery Challenge 319
excel-challenges
power-query
Transpose the table as shown. Transpose the table as shown

Challenge Description
Transpose the table as shown. Transpose the table as shown
Solutions
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 = "300-399/319/PQ_Challenge_319.xlsx"
input = pd.read_excel(path, sheet_name=1, usecols="A:I", nrows=4)
test = pd.read_excel(path, sheet_name=1, usecols="A:F", skiprows=8, nrows=10)
input_long = input.melt(id_vars='Fruits', var_name='Q_value')
input_long[['Q', 'Type']] = input_long['Q_value'].str.split('-', expand=True)
input_wide = input_long.pivot(index=['Fruits', 'Q'], columns='Type', values='value').reset_index()
input_wide[['Price', 'Quantity']] = input_wide[['Price', 'Quantity']].apply(pd.to_numeric)
input_wide['Total'] = input_wide['Price'] * input_wide['Quantity']
result_long = input_wide.melt(id_vars=['Fruits', 'Q'], value_vars=['Price', 'Quantity', 'Total'],
var_name='Quarters', value_name='Values')
result = result_long.pivot(index=['Fruits', 'Quarters'], columns='Q', values='Values').reset_index()
result['Fruits'] = result.groupby('Fruits')['Fruits'].transform(lambda x: [x.iloc[0]] + [None]*(len(x)-1))
print(result.equals(test)) # TrueLogic:
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
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.