library(tidyverse)
library(readxl)
path = "Power Query/300-399/316/PQ_Challenge_316.xlsx"
input = read_excel(path, range = "A1:C18")
test = read_excel(path, range = "E1:H8")
result = input %>%
fill(Continent, .direction = "down") %>%
mutate(r = (row_number() + 2) %/% 3, .by = Continent) %>%
unite("Country", Country, Medals, sep = "-") %>%
mutate(nr = row_number(), .by = c(Continent, r)) %>%
pivot_wider(names_from = nr, names_glue = "Country{nr}", values_from = Country) %>%
select(-r)
all.equal(result, test)
# there is a mistake in provided solution. UK is missing.Excel BI - PowerQuery Challenge 316

Challenge Description
Transpose the problem table into result table where only 3 countries can come in a row. If more than 3 countries, then insert rows for every 3 countries.
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/316/PQ_Challenge_316.xlsx"
input = pd.read_excel(path, usecols="A:C", nrows=17)
test = pd.read_excel(path, usecols="E:H", nrows=7).rename(columns=lambda c: c.replace('.1', ''))
input['Continent'] = input['Continent'].ffill()
input['row_in_continent'] = input.groupby('Continent').cumcount() + 1
input['r'] = ((input['row_in_continent'] + 2) // 3)
input['Country'] = input['Country'] + '-' + input['Medals'].astype(str)
input['nr'] = input.groupby(['Continent', 'r']).cumcount() + 1
result = (
input
.pivot_table(index=['Continent', 'r'], columns='nr', values='Country', aggfunc='first')
.reset_index()
)
result.columns = ['Continent', 'r'] + [f'Country{col}' for col in result.columns[2:]]
result = result.drop(columns='r')
result = result[result.columns[:len(test.columns)]]
print(result)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.