Find the best and worst months from daily sales data in pandas
Quick Overview
Write a pandas function that rolls daily sales up to monthly totals and reports the best and worst months with their percentage gap from the average month. It tests time-based resampling, a deterministic tie rule and returning a frame with exact columns and dtypes.
Find the best and worst months from daily sales data in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `best_worst_periods(df)` taking a DataFrame with a `date` column (`datetime64[ns]`, daily) and a numeric `sales` column. Aggregate to monthly totals and return a 2-row DataFrame describing the best and worst months.
Requirements:
- Resample `sales` to monthly totals with the alias `'ME'` (month-end timestamps).
- Columns: `label` (object), `month` (`datetime64[ns]`), `sales` (`float64`), `pct_vs_avg` (`float64`).
- Exactly 2 rows in the order `['best', 'worst']` with a 0..1 `RangeIndex`.
- `pct_vs_avg` = month total / mean monthly total - 1, rounded to 4 decimal places.
- Ties on the extreme value: report the earlier month.
Example:
```python
# daily data whose monthly totals are Jan=100, Feb=200, Mar=300 (mean = 200)
# best = Mar, worst = Jan
label month sales pct_vs_avg
0 best 2026-03-31 300.0 0.5
1 worst 2026-01-31 100.0 -0.5
```
```hint Watch the tie rule
Check which month the pandas lookup methods return when two months share the extreme total, and whether the resampled months come out in date order.
```
### What a Strong Answer Covers
- Aggregating the daily rows to month-end totals with the specified alias.
- Finding the peak and trough months under the required tie rule.
- Computing `pct_vs_avg` against the mean monthly total, rounded as specified.
- Returning exactly the required columns, dtypes, row order and index.
- Edge cases such as months with no rows, a single month and a mean of zero.
### Follow-up Questions
- How would you also report the median-vs-mean gap to flag skew?
- What changes if some months have missing days?
- How would you generalize this to the top and bottom k months?
Overview: Write a pandas function that rolls daily sales up to monthly totals and reports the best and worst months with their percentage gap from the average month. It tests time-based resampling, a deterministic tie rule and returning a frame with exact columns and dtypes.
Write best_worst_periods(df) taking a DataFrame with a date column (datetime64[ns], daily) and a numeric sales column. Aggregate to monthly totals and return a 2-row DataFrame describing the best and worst months.
Requirements:
Resample
sales
to monthly totals with the alias
'ME'
(month-end timestamps).