library(tidyverse)
library(readxl)
path = "files/CH-192 Table Transformation.xlsx"
input = read_excel(path, range = "B2:D12")
test = read_excel(path, range = "B15:D18")
result = input %>%
mutate(sign = sign(Quantity)) %>%
mutate(group = ceiling(cumsum(sign != lag(sign, default = 0))/2), .by = Product) %>%
summarise(Quantity = sum(Quantity),
Date = min(Date),
.by = c(Product,group)) %>%
filter(Quantity != 0) %>%
select(Date, Product, Quantity)
all.equal(result, test)
#> [1] TRUEOmid - Challenge 192
data-challenges
advanced-exercises
🔰 Transformation!

Challenge Description
🔰 Transformation!
Solutions
Logic:
Reads the workbook ranges needed for the challenge
Aggregates or ranks values at the relevant grouping level
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 numpy as np
path = "CH-192 Table Transformation.xlsx"
input = pd.read_excel(path, usecols="B:D", skiprows=1, nrows=11)
test = pd.read_excel(path, usecols="B:D", skiprows=14, nrows=4)
input['sign'] = np.sign(input['Quantity'])
input['group'] = input.groupby('Product')['sign'].apply(lambda x: (x != x.shift()).cumsum()).reset_index(level=0, drop=True)
input['group'] = np.ceil(input['group']/2)
result = input.groupby(['Product', 'group']).agg({'Quantity': 'sum', 'Date': 'min'}).reset_index()
result = result[result['Quantity'] != 0][['Date', 'Product', 'Quantity']].sort_values(by = "Date").reset_index(drop= True)
print(result.equals(test)) # TrueLogic:
Reads the workbook ranges needed for the challenge
Aggregates or ranks values at the relevant grouping level
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 business rule is readable, but the workbook still requires careful implementation to reach the expected layout.