Excel BI - PowerQuery Challenge 306

excel-challenges
power-query
Month Karen Shirley Lawrence Christian Customer
Published

March 24, 2026

Illustration for Excel BI - PowerQuery Challenge 306

Challenge Description

Month Karen Shirley Lawrence Christian Customer

Solutions

library(tidyverse)
library(readxl)

path = "Power Query/300-399/306/PQ_Challenge_306.xlsx"
input = read_excel(path, range = "A1:E7")
test  = read_excel(path, range = "G1:N5")

result = input %>%
  pivot_longer(-c(1), names_to = "Customer") %>%
  mutate(Amt = min(value[value > 0], na.rm = TRUE), 
         EMI = value/Amt,
         .by = Customer) %>%
  select(-value) %>%
  pivot_wider(names_from = Month, values_from = EMI)

all.equal(result, test, check.attributes = FALSE)  
# > [1] TRUE
  • 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 = "300-399/306/PQ_Challenge_306.xlsx"
input = pd.read_excel(path, usecols="A:E", nrows=7)
test = pd.read_excel(path, usecols="G:N", nrows=4).sort_values(by="Customer").reset_index(drop=True)

result = (input.melt(id_vars=input.columns[0], var_name="Customer", value_name="v")
    .assign(Amt=lambda df: df.groupby("Customer")["v"].transform(lambda x: x[x > 0].min()),
            EMI=lambda df: df["v"] / df["Amt"])
    .pivot_table(index=["Customer", "Amt"], columns=input.columns[0], values="EMI", aggfunc="first")
    .reset_index().reindex(columns=["Customer", "Amt"] + list(input[input.columns[0]].unique())))
result.columns.name = None
result = result.map(lambda x: int(x) if pd.notnull(x) and isinstance(x, (int, float)) else x)

print(result.equals(test)) # 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

    • Builds helper columns that drive the final output

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