library(tidyverse)
library(readxl)
path = "Power Query/200-299/291/PQ_Challenge_291.xlsx"
input = read_excel(path, range = "A1:D49")
test = read_excel(path, range = "F1:I29")
result = input %>%
fill(Company, Target) %>%
filter(cumsum(Sales) <= Target, .by = Company) %>%
mutate(
Company = ifelse(row_number() == 1, Company, NA),
Target = ifelse(row_number() == 1, Target, NA),
.by = Company
)
all.equal(result, test, heck.attributes = FALSE)
# TRUExcel BI - PowerQuery Challenge 291
excel-challenges
power-query
Company Target Month Sales Walmart Jan

Challenge Description
Company Target Month Sales Walmart Jan
Solutions
Logic:
Reads the workbook range needed for the challenge
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 = "200-299/291/PQ_Challenge_291.xlsx"
input = pd.read_excel(path, sheet_name=0, usecols="A:D", nrows=49)
test = pd.read_excel(path, sheet_name=0, usecols="F:I", nrows=28).rename(columns=lambda x: x.replace('.1', ''))
input[['Company', 'Target']] = input[['Company', 'Target']].ffill()
input['Cumulative Sales'] = input.groupby('Company')['Sales'].cumsum()
result = input[input['Cumulative Sales'] <= input['Target']].reset_index(drop=True)
result.loc[result.groupby('Company').cumcount() != 0, ['Company', 'Target']] = np.nan
result = result.drop(columns='Cumulative Sales')
print(result.equals(test))
# TRUELogic:
Reads the workbook range needed for the challenge
Aggregates or ranks values at the relevant grouping level
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 easy to moderate:
- The transformation rule is readable, but the final layout still requires a careful implementation.