library(tidyverse)
library(readxl)
excel_path <- "Power Query/300-399/339/PQ_Challenge_339.xlsx"
input = read_excel(excel_path, range = "A1:A7")
test = read_excel(excel_path, range = "C1:F7")
result = input %>%
mutate(
Country = str_extract(Data, "^[A-Z][a-z]+\\s+([A-Z][a-z]+)?") %>% trimws(),
`Time Zone` = str_extract(Data, '(?<=\\().+?(?=\\))'),
Latitude = as.numeric(str_extract(Data, "(?<=LAT )-?[\\d.]+")),
Longitude = as.numeric(str_extract(Data, "(?<=LONG )-?[\\d.]+"))
) %>%
select(-Data)
all.equal(result, test)
# [1] TRUEExcel BI - PowerQuery Challenge 339
excel-challenges
power-query
Pivot the table as shown.

Challenge Description
Pivot the table as shown.
Solutions
Logic:
Reads the workbook range needed for the challenge
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 re
excel_path = "Power Query/300-399/339/PQ_Challenge_339.xlsx"
input = pd.read_excel(excel_path, usecols="A:A", nrows=7)
test = pd.read_excel(excel_path, usecols="C:F", nrows=7)
result = pd.DataFrame({
"Country": input["Data"].map(
lambda s: (re.match(r"^[A-Z][a-z]+(?:\s+[A-Z][a-z]+)?", s).group(0).strip() if re.match(r"^[A-Z][a-z]+(?:\s+[A-Z][a-z]+)?", s) else None)
),
"Time Zone": input["Data"].map(
lambda s: (re.search(r"\((.+?)\)", s).group(1) if re.search(r"\((.+?)\)", s) else None)
),
"Latitude": input["Data"].map(
lambda s: (float(re.search(r"LAT (-?[\d.]+)", s).group(1)) if re.search(r"LAT (-?[\d.]+)", s) else None)
),
"Longitude": input["Data"].map(
lambda s: (float(re.search(r"LONG (-?[\d.]+)", s).group(1)) if re.search(r"LONG (-?[\d.]+)", s) else None)
),
})
print(result.equals(test))Logic:
Reads the workbook range needed for the challenge
Uses direct pattern parsing where the workbook encodes logic in text
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.