Pivot sales and units by store and date into two-level columns in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `pivot_multi_value(df)` for a frame with columns `'store'` (str), `'metric_date'` (str), `'sales'` (int) and `'units'` (int). Return a wide table with one row per store and one column per (metric, date) pair, holding the total sales and total units for each store on each date.
Requirements:
- Rows that share a store and date are summed into one cell.
- Missing store/date combinations are filled with `0`.
- The column MultiIndex stays intact: the top level is the value name (`'sales'`, `'units'`), the second level is the date (level name `'metric_date'`).
- Keep `'store'` as the index: no `reset_index()`, flattening, or renaming.
- Stores, metrics and dates appear in sorted order.
Example:
```python
df = pd.DataFrame({
'store': ['A', 'A', 'A', 'B'],
'metric_date': ['2024-01', '2024-02', '2024-02', '2024-02'],
'sales': [100, 30, 20, 80],
'units': [10, 3, 2, 8],
})
result = pivot_multi_value(df)
# sales units
# metric_date 2024-01 2024-02 2024-01 2024-02
# store
# A 100 50 10 5
# B 0 80 0 8
list(result.columns)
# [('sales', '2024-01'), ('sales', '2024-02'),
# ('units', '2024-01'), ('units', '2024-02')]
```
Store A has two rows for 2024-02, so its cells there are 30 + 20 = 50 sales and 3 + 2 = 5 units. Store B has no 2024-01 rows, so both of its 2024-01 cells are 0.
```hint Duplicates decide the tool
The input can hold several rows for the same store and date. Pick a reshaping method that aggregates while it pivots, and check how it handles more than one value column.
```
### What a Strong Answer Covers
- Summing repeated store/date rows during the reshape, and knowing which pandas defaults would raise on them or average them
- A two-level column index with the metric name on top and the date below
- Zero-filled cells for store/date pairs with no rows
- `'store'` left as the index, with the column labels neither flattened nor renamed
- How the order of rows and columns is set, and why `'YYYY-MM'` strings sort in date order
### Follow-up Questions
- How would you flatten the MultiIndex columns to `'sales_2024-01'` style names if a caller needed a flat frame?
- What changes if a store/date pair has multiple rows?
- How would you regroup the columns so each date holds its sales and units side by side?
- What breaks if `metric_date` holds strings like `'1/15/2024'`?
Overview: Reshape a store sales table so each store is a row and each metric and date pair is a column, summing repeated rows and filling gaps with zero. It tests multi-value pivoting in pandas, aggregation defaults and two-level column indexes.