Total Monthly Sales per Store With pandas groupby and pd.Grouper
Quick Overview
Write a pandas function that totals sales per store per calendar month and returns a Series indexed by store and month-end date. It tests groupby with pd.Grouper, frequency aliases, index level order, and how a categorical key changes which rows appear.
Total Monthly Sales per Store With pandas groupby and pd.Grouper
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `monthly_sales_by_store(df: pd.DataFrame) -> pd.Series`. The input has a `datetime64[ns]` column `'date'`, a categorical `'store'` and a numeric `'sales'`. Return total `'sales'` per store per calendar month. The `'date'` column is already `datetime64[ns]`, so no parsing is required.
The function must meet these requirements:
- Aggregate with `df.groupby(['store', pd.Grouper(key='date', freq='ME')])['sales'].sum()`.
- Return a `pd.Series` with a 2-level `MultiIndex`, level order `['store', 'date']`.
- Each `'date'` label is the month-end timestamp.
- Include only the store-month pairs that have at least one row in `df`, as the example shows.
Example:
```python
df = pd.DataFrame({
'date': pd.to_datetime(['2024-01-05', '2024-01-20', '2024-02-03', '2024-01-11']),
'store': ['A', 'A', 'A', 'B'],
'sales': [10, 5, 7, 3],
})
monthly_sales_by_store(df)
# store date
# A 2024-01-31 15
# 2024-02-29 7
# B 2024-01-31 3
# Name: sales, dtype: int64
```
Store A's two January rows add up to 15. Its February row lands in the bucket labeled 2024-02-29 because 2024 is a leap year. Store B has one January row and no February row, so `(B, 2024-02-29)` does not appear.
```hint Categorical keys
`store` is categorical. Check what `groupby` does by default with category values, or combinations of keys, that never occur in the data.
```
### What a Strong Answer Covers
- Grouping by a categorical key and a monthly time bucket in a single `groupby` call.
- How the order of the grouping keys sets the order of the index levels.
- Why the labels come out as month-end timestamps and which setting controls that.
- How the categorical `store` column interacts with the `observed` setting and what that does to the rows in the output.
### Follow-up Questions
- How would you keep the `'date'` level as month-start labels instead?
- How would you produce a store-by-month wide table from this Series?
- Why prefer `pd.Grouper` over `resample` here?
Overview: Write a pandas function that totals sales per store per calendar month and returns a Series indexed by store and month-end date. It tests groupby with pd.Grouper, frequency aliases, index level order, and how a categorical key changes which rows appear.
Implement monthly_sales_by_store(df: pd.DataFrame) -> pd.Series. The input has a datetime64[ns] column 'date', a categorical 'store' and a numeric 'sales'. Return total 'sales' per store per calendar month. The 'date' column is already datetime64[ns], so no parsing is required.
The function must meet these requirements:
Aggregate with
df.groupby(['store', pd.Grouper(key='date', freq='ME')])['sales'].sum()
.
Return a
pd.Series
with a 2-level
MultiIndex
, level order
['store', 'date']
.
Each
'date'
label is the month-end timestamp.
Include only the store-month pairs that have at least one row in
df
, as the example shows.
Example:
df = pd.DataFrame({
'date': pd.to_datetime(['2024-01-05', '2024-01-20', '2024-02-03', '2024-01-11']),
'store': ['A', 'A', 'A', 'B'],
'sales': [10, 5, 7, 3],
})
monthly_sales_by_store(df)
# store date
# A 2024-01-31 15
# 2024-02-29 7
# B 2024-01-31 3
# Name: sales, dtype: int64
Store A's two January rows add up to 15. Its February row lands in the bucket labeled 2024-02-29 because 2024 is a leap year. Store B has one January row and no February row, so (B, 2024-02-29) does not appear.
What a Strong Answer Covers Guidance
Grouping by a categorical key and a monthly time bucket in a single
groupby
call.
How the order of the grouping keys sets the order of the index levels.
Why the labels come out as month-end timestamps and which setting controls that.
How the categorical
store
column interacts with the
observed
setting and what that does to the rows in the output.
Follow-up Questions Guidance
How would you keep the
'date'
level as month-start labels instead?
How would you produce a store-by-month wide table from this Series?