library(tidyverse)
library(readxl)
path = "files/200-299/237/CH-237 Table Transformation.xlsx"
input = read_excel(path, range = "B2:E10")
test = read_excel(path, range = "H2:O6")
result = input %>%
mutate(rn = row_number(), .by = Doc) %>%
pivot_wider(
names_from = rn,
values_from = c(Code, Num),
names_sep = "",
names_vary = "slowest"
)
all.equal(result, test)
#> [1] TRUEOmid - Challenge 237
data-challenges
advanced-exercises
🔰 Table Transformation!

Challenge Description
🔰 Table Transformation!
Solutions
Logic:
Reads the workbook ranges needed for the challenge
Reshapes the data into the grain required by the task
Builds the intermediate columns that drive the final result
Strengths:
- The R solution stays close to the workbook rule and keeps the transformation compact.
Areas for Improvement:
- The code assumes the sheet structure and source ranges remain stable.
Gem:
- The strongest part of the solution is choosing the right intermediate representation before shaping the final output.
import pandas as pd
import re
path = "200-299/237/CH-237 Table Transformation.xlsx"
input = pd.read_excel(path, sheet_name=0, usecols="B:E", skiprows=1, nrows=8)
test = pd.read_excel(path, sheet_name=0, usecols="H:O", skiprows=1, nrows=4).rename(columns=lambda col: col.replace('.1', ''))
input['rn'] = input.groupby(['Doc', 'Status']).cumcount() + 1
result = input.pivot_table(
index=['Doc', 'Status'],
columns='rn',
values=['Code', 'Num'],
aggfunc='first'
)
result.columns = [f"{col[0]}{col[1]}" for col in result.columns]
def sort_key(col):
m = re.match(r'(Code|Num)(\d+)', col)
if m:
return int(m.group(2)), 0 if m.group(1) == 'Code' else 1
return (float('inf'), col)
result = result.reindex(sorted(result.columns, key=sort_key), axis=1)
result['Num1'] = result['Num1'].astype(int)
result = result.reset_index()
print(result.equals(test)) # TrueLogic:
Reads the workbook ranges needed for the challenge
Reshapes the data into the grain required by the task
Aggregates or ranks values at the relevant grouping level
Parses the text patterns directly instead of relying on manual cleanup
Strengths:
- The Python version follows the same rule in a direct dataframe-oriented implementation.
Areas for Improvement:
- The code assumes the workbook layout remains stable, so any sheet redesign would require small adjustments.
Gem:
- The implementation stays close to the original workbook rule instead of adding unnecessary abstraction.
Difficulty Level
This task is moderate:
The core logic is clear, but the correct transformation pattern is not obvious from the raw input.
The challenge combines multiple reshaping, grouping, or parsing steps.