Stack & Unstack
Python · Reshaping & Workflow
Theory
stack() and unstack() reshape using the index instead of columns. unstack() moves the innermost row-index level into the columns: after s = df.groupby(['city', 'quarter'])['amount'].sum(), which has a two-level (city, quarter) MultiIndex, s.unstack() gives one row per city and one column per quarter. unstack('city') or unstack(0) moves a different level, and fill_value=0 fills combinations that did not exist.
stack() does the opposite: it moves the column labels into the innermost row-index level, turning a wide table into a long Series with a MultiIndex. In pandas 2.x stack drops missing values by default (a future_stack=True option previews the newer behaviour). In practice unstack is most common right after a multi-key groupby, to view the result as a grid, and reset_index() turns any MultiIndex result back into ordinary columns.
Why we use it
Multi-key groupbys produce long results with a MultiIndex that are hard to read. unstack turns them into a grid in one call, and stack goes back, without having to name index and columns as pivot does.
When to use it
Use unstack directly after groupby on two or more keys, when you want one key across the columns. Use pivot_table when starting from plain columns, and melt for column-to-row reshaping of ordinary DataFrames.
How it works
- Series with MultiIndex (city, quarter)
- Pick the level to move: innermost by default
- unstack(): that level's values become columns
- Some combinations missing? Yes: fill_value=0 or leave NaN. No: Grid is complete.
- Grid: cities x quarters (stack() reverses it)
Syntax
s.unstack(level=-1, fill_value=None)
df.stack()
df.groupby(['k1', 'k2'])['v'].sum().unstack(fill_value=0)
df.reset_index()Example
grid = df.groupby(['city', 'quarter'])['amount'].sum().unstack(fill_value=0)
print(grid)Key points
- unstack moves an index level into columns; stack moves columns into the index
- Default level is the innermost (-1); pass a name or number to choose
- unstack(fill_value=0) fills missing combinations
- Common pair: groupby([k1, k2]).sum().unstack()
- reset_index() turns a MultiIndex result into normal columns