GroupBy Aggregation: Sum and Mean

mediumpandas_exploration

Implement two aggregation functions.

total_per_group(df, group_col, value_col) Return the sum of value_col for each group in group_col as a pd.Series.

mean_per_group(df, group_col, value_col) Return the mean of value_col for each group in group_col as a pd.Series.

.apply() is not allowed — use groupby().sum() / groupby().mean() directly.

df = pd.DataFrame({
    "city": ["London","London","NY","NY","Tokyo"],
    "sales": [7000, 2000, 7000, 5000, 5000],
})
total_per_group(df, "city", "sales")
# city
# London    9000
# NY       12000
# Tokyo     5000
# Name: sales, dtype: int64
Constraints
  • no apply

Your solution

Edit total_per_group and run the real pytest suite in your browser — no install required. Your code is saved locally.

⌘/Ctrl + ↵

Loading the Python runtime (first run only)…

Hints

Hint 1

df.groupby(col)[value_col] selects the value column within each group.

Hint 2

Chain .sum() or .mean() directly on the GroupBy object — no need for .apply().

Hint 3

The result is a Series indexed by the group values.