Pivot a tidy pandas DataFrame to wide form with a flat date column
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write a function `long_to_wide(df)` that reshapes a long DataFrame with columns `'date'` (str), `'metric'` (str), and `'value'` (float) into wide form. Each `(date, metric)` pair is unique, so use `DataFrame.pivot`. `pivot_table` aggregates, and nothing here needs aggregating.
Requirements:
- Use `df.pivot(index='date', columns='metric', values='value')`.
- Drop the columns axis name via `rename_axis(columns=None)`.
- Call `reset_index()` so `'date'` is a normal column.
- Final columns: `['date', <each distinct metric sorted>]`.
- Missing `(date, metric)` combinations stay `NaN`.
Example:
```python
df = pd.DataFrame({
'date': ['2026-01-01', '2026-01-01', '2026-01-02'],
'metric': ['clicks', 'views', 'clicks'],
'value': [3.0, 10.0, 5.0],
})
long_to_wide(df)
# date clicks views
# 0 2026-01-01 3.0 10.0
# 1 2026-01-02 5.0 NaN
```
```hint Look at the header
Print the columns and the index right after the pivot and compare them with the final layout. Two things still differ: the name on the columns axis and where `date` lives.
```
### What a Strong Answer Covers
- The `pivot` call that maps `date`, `metric` and `value` to the index, the columns and the values, with no aggregation.
- Why the columns axis name has to be removed and how the output looks if it stays.
- How `date` moves from the index back to a regular first column, and where the sorted metric order comes from.
- What missing combinations become, and what happens when a pair is not unique.
### Follow-up Questions
- Why does `pivot` raise if a `(date, metric)` pair is duplicated?
- How would you fill the `NaN` gaps with 0?
- How would you put the metric columns in a fixed business order that is not alphabetical?
Overview: Write a pandas function that turns a long DataFrame of date, metric and value rows into a wide table with a date column followed by one column per metric. It tests the pivot call, cleaning up the column axis name and the index, and how missing pairs and repeated keys behave.