Pivot sales into a region-by-month grid with pandas pivot_table
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `sales_by_region_month(df)` that pivots `df` (columns `region` as str, `month` as str, `sales` as int) into a region-by-month grid and returns it as a flat DataFrame.
The result must meet these requirements:
- Call `pd.pivot_table` with `index='region'`, `columns='month'`, `values='sales'`, `aggfunc='sum'`, `fill_value=0`.
- Missing region and month combinations become `0`.
- Use `reset_index()` and `rename_axis(columns=None)` so `region` is a column and no columns axis name remains.
- The final columns are `['region', <each month sorted>]` and the value columns keep an integer dtype. Months are sorted as strings, so `Feb` comes before `Jan`, as the example shows.
For example:
```python
df = pd.DataFrame({
'region': ['East', 'East', 'West'],
'month': ['Jan', 'Feb', 'Jan'],
'sales': [10, 20, 5],
})
sales_by_region_month(df)
# region Feb Jan
# 0 East 20 10
# 1 West 0 5
```
```hint Look at what the pivot leaves behind
Before flattening, print the pivot's index, the name on its columns axis, and its dtypes. Each requirement after the `pivot_table` call removes one of those leftovers or protects the dtype.
```
### What a Strong Answer Covers
- How the long table is aggregated into the grid, and what happens to region and month pairs with no rows.
- Why the value columns stay integer and what would turn them into floats.
- How the result is flattened: `region` becomes a column and the columns axis name is removed.
- The order of the month columns and of the rows.
### Follow-up Questions
- How would you add a per-region total column?
- What changes if `sales` contains NaN values?
- How would you order the month columns by calendar month instead of alphabetically?
Overview: Write a pandas function that reshapes long sales records into a region-by-month grid, fills missing combinations with zero, and returns a flat DataFrame. It tests pivot tables, cleaning up the index and the columns axis name, column order, and keeping integer dtypes.