Excel BI - PowerQuery Challenge 317

excel-challenges
power-query
Transpose the given data from Problem Table into Result table as shown
Published

March 24, 2026

Illustration for Excel BI - PowerQuery Challenge 317

Challenge Description

Transpose the given data from Problem Table into Result table as shown

Solutions

library(tidyverse)
library(readxl)

path = "Power Query/300-399/317/PQ_Challenge_317.xlsx"
input = read_excel(path, range = "A1:C12")
test  = read_excel(path, range = "E1:F13")

result = input %>% 
  fill(Country, State) %>%
  summarise(Cities = paste0(Cities, collapse = ", "), .by = c(Country, State)) %>%
  mutate(Country = ifelse(row_number() == 1, Country, ""), .by = Country) %>%
  pivot_longer(everything(), names_to = "Data1", values_to = "Data2") %>%
  filter(Data2 != "") 

all.equal(result, test)
# > [1] 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

    • 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/317/PQ_Challenge_317.xlsx"
input = pd.read_excel(path, usecols="A:C", nrows=12)
test = pd.read_excel(path, usecols="E:F", nrows=13)

input[['Country', 'State']] = input[['Country', 'State']].ffill()
result = (
    input
    .groupby(['Country', 'State'], as_index=False, sort=False)
    .agg({'Cities': lambda x: ', '.join(x.dropna().astype(str))})
)
result['Country'] = result.groupby('Country', sort=False).apply(
    lambda g: [g['Country'].iloc[0]] + [''] * (len(g) - 1)
).explode(ignore_index=True).values

output = []
for idx, row in result.iterrows():
    for col in ['Country', 'State', 'Cities']:
        output.append({'Data1': col, 'Data2': row[col]})
output = pd.DataFrame(output)
output = output[output['Data2'] != ""].reset_index(drop=True)

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

    • Reads the workbook range needed for the challenge

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