library(tidyverse)
library(readxl)
path = "Power Query/200-299/290/PQ_Challenge_290.xlsx"
input = read_excel(path, range = "A1:B12")
test = read_excel(path, range = "D1:H4")
result = input %>%
mutate(group = cumsum(Column1 == "Company")) %>%
pivot_wider(names_from = "Column1", values_from = "Column2") %>%
select(Company, Revenue, Cost, Tax, Profit) %>%
mutate(across(-Company, as.integer)) %>%
mutate(
Tax = ifelse(is.na(Tax), 0, Tax),
Profit = ifelse(is.na(Profit), (Revenue - Cost - Tax), Profit)
)Excel BI - PowerQuery Challenge 290
excel-challenges
power-query
Generate the result table where Profit = Revenue - Cost - Tax. Profit needs to be calculated if profit is not given.

Challenge Description
Generate the result table where Profit = Revenue - Cost - Tax. Profit needs to be calculated if profit is not given.
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 = "200-299/290/PQ_Challenge_290.xlsx"
input = pd.read_excel(path, usecols="A:B", nrows=12)
test = pd.read_excel(path, usecols="D:H", nrows=3)
input['group'] = (input['Column1'] == 'Company').cumsum()
result = input.pivot(index='group', columns='Column1', values='Column2').reset_index(drop=True)
result['Tax'] = result['Tax'].fillna(0).astype(int)
result['Profit'] = result.apply(
lambda r: r['Revenue'] - r['Cost'] - r['Tax'] if pd.isna(r['Profit']) else r['Profit'], axis=1
).astype(int)
result = result[['Company', 'Revenue', 'Cost', 'Tax', 'Profit']]
result.columns.name = None
for col in ['Revenue', 'Cost']:
result[col] = result[col].astype(int)
print(result.equals(test)) # TrueLogic:
Reads the workbook range needed for the challenge
Reshapes the data into the structure required by the result table
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.