Excel BI - PowerQuery Challenge 344

excel-challenges
power-query
Pivot the given table. Also create a new column Sold = Starting Stock + Received - Next month’s starting stock.
Published

March 24, 2026

Illustration for Excel BI - PowerQuery Challenge 344

Challenge Description

Pivot the given table. Also create a new column Sold = Starting Stock + Received - Next month’s starting stock.

Solutions

library(tidyverse)
library(readxl)

path <- "Power Query/300-399/344/PQ_Challenge_344.xlsx"
input <- read_excel(path, range = "A1:A17")
test <- read_excel(path, range = "C1:I16")

result = input %>%
  rename(Value = 1) %>%
  filter(!is.na(Value)) %>%
  mutate(
    Location = ifelse(
      str_detect(Value, "Location"),
      str_replace_all(Value, "Location: ", ""),
      NA
    )
  ) %>%
  fill(Location) %>%
  filter(!str_detect(Value, "Location")) %>%
  separate_wider_delim(
    Value,
    delim = ",",
    names_sep = "_",
    too_few = "align_start"
  ) %>%
  rename(
    Category = Value_1,
    SKU = Value_2,
    Jan_Stock = Value_3,
    Jan_Received = Value_4,
    Feb_Stock = Value_5,
    Feb_Received = Value_6,
    Mar_Stock = Value_7,
    Mar_Received = Value_8
  ) %>%
  select(Location, everything(), -Value_9) %>%
  filter(Category != "Category") %>%
  pivot_longer(
    cols = -c(Location, Category, SKU),
    names_to = c("Month", ".value"),
    names_sep = "_"
  ) %>%
  filter(Stock != "") %>%
  mutate(
    `Starting Stock` = as.integer(Stock),
    `Received Stock` = as.integer(Received)
  ) %>%
  select(-c(Stock, Received)) %>%
  mutate(
    Sold = `Starting Stock` + `Received Stock` - lead(`Starting Stock`),
    .by = c(Location, Category)
  )


all.equal(result, test)
  • 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

    • 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 numpy as np

input = pd.read_excel("Power Query/300-399/344/PQ_Challenge_344.xlsx", usecols="A", nrows=17, header=None, names=["Value"]).dropna()
test = pd.read_excel("Power Query/300-399/344/PQ_Challenge_344.xlsx", usecols="C:I", nrows=15)

input["Location"] = np.where(input["Value"].str.contains("Location"), input["Value"].str.replace("Location: ", "", regex=False), np.nan)
input["Location"] = input["Location"].ffill()
input = input[~input["Value"].str.contains("Location")]

split_cols = input["Value"].str.split(",", expand=True).rename(columns={0:"Category",1:"SKU",2:"Jan_Stock",3:"Jan_Received",4:"Feb_Stock",5:"Feb_Received",6:"Mar_Stock",7:"Mar_Received"})
input = pd.concat([input[["Location"]], split_cols], axis=1)
input = input[input["Category"] != "Category"]

long = input.melt(id_vars=["Location","Category","SKU"], value_vars=["Jan_Stock","Jan_Received","Feb_Stock","Feb_Received","Mar_Stock","Mar_Received"], var_name="Month_Type", value_name="Value")
long[["Month","Type"]] = long["Month_Type"].str.split("_", expand=True)
result = long.pivot_table(index=["Location","Category","SKU","Month"], columns="Type", values="Value", aggfunc="first").reset_index()
result = result[result["Stock"].notna() & (result["Stock"] != "")]
result[["Starting Stock","Received Stock"]] = result[["Stock","Received"]].astype(int)
result = result.drop(columns=["Stock","Received"])

result = result.reset_index(drop=True)
test = test.reset_index(drop=True)
location_order = ["North", "South", "East"]
month_order = ["Jan", "Feb", "Mar"]

result["Location"] = pd.Categorical(result["Location"], categories=location_order, ordered=True)
result["Month"] = pd.Categorical(result["Month"], categories=month_order, ordered=True)

result = result.sort_values(
    by=["Location", "Category", "SKU", "Month"],
    ascending=[True, True, True, True]
).reset_index(drop=True)

result['Location'] = result['Location'].astype(str)
result['Category'] = result['Category'].astype(str)
result['Month'] = result['Month'].astype(str)


result["Sold"] = (
    result["Starting Stock"] + result["Received Stock"] -
    result.groupby(["Location","Category"])["Starting Stock"].shift(-1)
)

print(test.equals(result)) # True
  • Logic:

    • Reads the workbook range needed for the challenge

    • Reshapes the data into the structure required by the result table

    • 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 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.