library(tidyverse)
library(readxl)
path = "Power Query/PQ_Challenge_271.xlsx"
input = read_excel(path, range = "A1:C19")
test = read_excel(path, range = "E1:H12")
result = input %>%
mutate(group_num = consecutive_id(Group)) %>%
mutate(Rank = dense_rank(-Revenue), .by = group_num) %>%
filter(group_num >= Rank) %>%
arrange(Group,Rank, Company) %>%
select(Group, Company, Revenue, Rank)
all.equal(result, test, check.attributes = FALSE)
#> [1] TRUEExcel BI - PowerQuery Challenge 271
excel-challenges
power-query
Group From first group, pick up top 1 on the basis of revenue, from second group, pick up top 2 and so on. First group is that which appears first, second group appears second….(Data is already sorted on Group). Insert a Rank column also.

Challenge Description
Group From first group, pick up top 1 on the basis of revenue, from second group, pick up top 2 and so on. First group is that which appears first, second group appears second….(Data is already sorted on Group). Insert a Rank column also.
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
path = "PQ_Challenge_271.xlsx"
input = pd.read_excel(path, usecols="A:C", nrows=19)
test = pd.read_excel(path, usecols="E:H", nrows=11).rename(columns=lambda col: col.split('.')[0])
input['Rank'] = (
input.groupby(
(input['Group'] != input['Group'].shift()).cumsum()
)['Revenue']
.rank(method='dense', ascending=False)
.astype('int64')
)
result = (
input[input['Rank'] <= (input['Group'] != input['Group'].shift()).cumsum()]
.sort_values(['Group', 'Rank', 'Company'])
[['Group', 'Company', 'Revenue', 'Rank']]
.reset_index(drop=True)
)
print(test.equals(result)) # 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.