library(tidyverse)
library(readxl)
path <- "300-399/330/CH-330 Custom Grouping.xlsx"
input <- read_excel(path, range = "B2:D13")
test <- read_excel(path, range = "H2:I8")
result <- input %>%
mutate(
p = as.numeric(`Start Date Time`) / 86400,
q = as.numeric(`End Date Time`) / 86400,
d = floor(q) - floor(p),
rep_num = case_when(
d > 2 ~ NA_real_,
d == 2 ~ floor(p) + 1,
(floor(p) + 1 - p) > (q %% 1) ~ floor(p),
TRUE ~ floor(q)
),
group = if_else(
is.na(rep_num),
"Uncategorzied",
as.character(as.Date(rep_num, origin = "1970-01-01"))
)
) %>%
summarise(
`AVG Polution Rate` = round(mean(Polution)),
.by = group
) %>%
arrange(group)
all.equal(result$`AVG Polution Rate`, test$`AVG Polution Rate`)
# [1] TRUEOmid - Challenge 330
data-challenges
advanced-exercises
🔰 : Custom Grouping!

Challenge Description
🔰 : Custom Grouping!
Solutions
Logic:
Reads the workbook ranges needed for the challenge
Aggregates or ranks values at the relevant grouping level
Builds the intermediate columns that drive the final result
Strengths:
- The R solution stays close to the workbook rule and keeps the transformation compact.
Areas for Improvement:
- The code assumes the sheet structure and source ranges remain stable.
Gem:
- The strongest part of the solution is choosing the right intermediate representation before shaping the final output.
import pandas as pd
import numpy as np
path = "300-399/330/CH-330 Custom Grouping.xlsx"
df = pd.read_excel(path, usecols="B:D", skiprows=1, nrows=12)
test = pd.read_excel(path, usecols="H:I", skiprows=1, nrows=6)
p = df["Start Date Time"].astype("int64") / (24*60*60*1_000_000_000)
q = df["End Date Time"].astype("int64") / (24*60*60*1_000_000_000)
b, c = np.floor(p), np.floor(q)
rep = np.where(
(c - b) > 2, np.nan,
np.where(
(c - b) == 2, b + 1,
np.where((b + 1 - p) > (q % 1), b, c)
)
)
df["group"] = np.where(
np.isnan(rep),
"Uncategorzied",
pd.to_datetime(rep, unit="D", origin="1970-01-01").strftime("%-m/%-d/%Y")
)
result = (
df.groupby("group")["Polution"]
.mean().round()
.reset_index(name="AVG Polution Rate")
.sort_values("group")
)
print((result['AVG Polution Rate'] == test['AVG Polution Rate']).all())
# TrueLogic:
Reads the workbook ranges needed for the challenge
Aggregates or ranks values at the relevant grouping level
Strengths:
- The Python version follows the same rule in a direct dataframe-oriented implementation.
Areas for Improvement:
- The code assumes the workbook layout remains stable, so any sheet redesign would require small adjustments.
Gem:
- The implementation stays close to the original workbook rule instead of adding unnecessary abstraction.
Difficulty Level
This task is moderate:
- The business rule is readable, but the workbook still requires careful implementation to reach the expected layout.