Reshape a long pandas DataFrame to wide form with pivot
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `def to_wide(df: pd.DataFrame) -> pd.DataFrame`. The input has columns `['date', 'metric', 'value']` with unique `('date', 'metric')` pairs. Reshape it to wide form: one row per date, one column per metric, with each cell holding `value`.
Requirements:
- Use `pivot`. Do not use `pivot_table`.
- The row index is the unique dates, named `date`.
- The columns are the distinct metrics, with the columns-axis name `metric`.
Example:
```python
import pandas as pd
df = pd.DataFrame({
"date": ["2026-01-01", "2026-01-01", "2026-01-02"],
"metric": ["cpu", "mem", "cpu"],
"value": [10, 20, 15],
})
to_wide(df)
# metric cpu mem
# date
# 2026-01-01 10.0 20.0
# 2026-01-02 15.0 NaN
```
```hint Three columns, three roles
One column becomes the row labels, one becomes the column labels, and one fills the cells. Check where `pivot` takes the axis names from before you write any renaming code.
```
### Constraints & Assumptions
- Each `(date, metric)` pair appears at most once, so every cell receives at most one value and nothing needs aggregating.
- Not every date has every metric. In the example, `2026-01-02` has no `mem` row, and that cell comes out as `NaN`.
### What a Strong Answer Covers
- Which input column goes to the index, the columns and the values of `pivot`, and why `values` should be passed explicitly.
- How the output gets its `date` index name and `metric` columns-axis name, and which extra steps (a reset or a rename) would break them.
- What a missing `(date, metric)` combination becomes in the output and how it changes the dtypes.
- How `pivot` and `pivot_table` differ, and what `pivot` does when the uniqueness assumption fails.
### Follow-up Questions
- Why does `pivot` raise if a `(date, metric)` pair repeats, and when would you switch to `pivot_table`?
- How would you fill the resulting `NaN` gaps for missing metric/date combinations?
- How would you turn the wide frame back into the original long table?
Overview: Write a pandas function that reshapes a long table of date, metric and value rows into a wide frame with one row per date and one column per metric. It tests how pivot assigns the index, columns and values, what happens to missing combinations and repeated keys, and when an aggregating pivot is the better choice.