Excel BI - PowerQuery Challenge 277

excel-challenges
power-query
Transpose the data as shown.
Published

March 24, 2026

Illustration for Excel BI - PowerQuery Challenge 277

Challenge Description

Transpose the data as shown.

Solutions

library(tidyverse)
library(readxl)

path = "Power Query/PQ_Challenge_277.xlsx"
input = read_excel(path, range = "A1:B10")
test  = read_excel(path, range = "D1:H4")

result = input %>%
  mutate(country = ifelse(is.na(Data2), Data1, NA)) %>%
  fill(country) %>% 
  na.omit() %>%
  separate_rows(c(Data1, Data2)) %>%
  mutate(Data2 = as.numeric(Data2)) %>%
  pivot_wider(names_from = Data1, values_from = Data2) 

all.equal(result, test, check.attributes = FALSE)
#> [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
import numpy as np

path = "PQ_Challenge_277.xlsx"

input = pd.read_excel(path, usecols="A:B", nrows=10)
test = pd.read_excel(path, usecols="D:H", nrows=3).sort_values(by='Country').reset_index(drop=True)

input['country'] = input['Data1'].where(input['Data2'].isna())
input['country'] = input['country'].fillna(method='ffill')
input = input.dropna()
input['Data1'] = input['Data1'].astype(str).str.split(', ')
input['Data2'] = input['Data2'].astype(str).str.split(', ')

input = input.explode(['Data1', 'Data2']).reset_index(drop=True)
input['Data2'] = pd.to_numeric(input['Data2'], errors='coerce')
input = input.pivot(index='country', columns='Data1', values='Data2').reset_index()
input = input.rename_axis(None, axis=1)
  • 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.