Write a pandas function that sums sales by calendar month with resample and returns a Series indexed by month-end dates, keeping empty months in the range. It tests DatetimeIndex resampling, frequency aliases, and how aggregations treat empty bins.
Implement `monthly_totals(df: pd.DataFrame) -> pd.Series`. The input has a `datetime64[ns]` column `'date'` and a numeric column `'sales'`. Return monthly sales sums as a Series indexed by month-end dates.
The function must meet these requirements:
- Compute `df.set_index('date').resample('ME')['sales'].sum()`.
- The result has a `DatetimeIndex` at `'ME'` frequency.
- Do not add or remove months by hand: every month between the first and last date appears, and empty months sum to 0.
Example:
```python
df = pd.DataFrame({
'date': pd.to_datetime(['2024-01-05', '2024-01-20', '2024-03-02']),
'sales': [100, 50, 30],
})
monthly_totals(df)
# date
# 2024-01-31 150
# 2024-02-29 0
# 2024-03-31 30
# Freq: ME, Name: sales, dtype: int64
```
The two January rows add up to 150. February has no rows, but it lies between the first and last date, so it appears with 0.
```hint Empty months
Check what `sum` returns for a month that has no rows, and compare it with what an aggregation such as `mean` returns for the same month.
```
### What a Strong Answer Covers
- Why `resample` needs a datetime index and how to get one from the `date` column.
- How month-end binning assigns each date to a bucket and labels it.
- Why empty months inside the date range appear and what value `sum` gives them.
- Which aggregation settings would give those months a different value.
### Follow-up Questions
- How would you return zero-filled months as `0` vs. `NaN`?
- How would you adapt this to fiscal-year or quarterly totals?
- How would you compute the same monthly totals separately for each store?
Overview: Write a pandas function that sums sales by calendar month with resample and returns a Series indexed by month-end dates, keeping empty months in the range. It tests DatetimeIndex resampling, frequency aliases, and how aggregations treat empty bins.
Implement monthly_totals(df: pd.DataFrame) -> pd.Series. The input has a datetime64[ns] column 'date' and a numeric column 'sales'. Return monthly sales sums as a Series indexed by month-end dates.