Sub topic 11
Moving index levels with stack and unstack
This chapter assumes you know groupby, reset_index, and how a MultiIndex (an index with more than one level) looks when printed. melt and pivot work on columns. stack and unstack do the same job on index levels, which is useful after a groupby has already put your keys into the index.
What the two methods do
unstackmoves one index level into the columns. The table gets wider.stackmoves the innermost column level into the index. The table gets longer.
By default, both act on the last level. You can pick another level by name or by position.
Unstack after a groupby
Grouping by two keys produces a Series with a two-level index. unstack turns the second key into columns.
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
indexed = sales.groupby(["store", "month"])["sales"].sum()
print(indexed)
print(indexed.unstack("month"))The first print shows a Series with a (store, month) index and these values: A/jan 100, B/feb 90, B/jan 80. The second print shows a table with columns feb and jan:
month feb jan
store
A NaN 100.0
B 90.0 80.0Store A has no February row, so that cell is NaN. Because of the NaN, pandas converts the integers to floats. To fill the gap and keep integers, pass fill_value:
wide = indexed.unstack("month", fill_value=0)
print(wide)Choosing the level
A level can be given by name or by position. Position 0 is the outermost level.
print(indexed.unstack(0))This moves store into the columns instead, so the rows are months and the columns are stores.
Stacking back
stack reverses the move. It turns the column labels back into an index level.
long = wide.stack()
print(long)
frame = long.reset_index(name="sales")
print(frame)stack returns a Series with a (store, month) index. reset_index(name="sales") turns that Series into an ordinary long DataFrame with columns store, month and sales.
Comparing with pivot and melt
| Task | Column-based tool | Index-based tool |
|---|---|---|
| Long to wide | `pivot` | `unstack` |
| Wide to long | `melt` | `stack` |
| Handles duplicate keys | `pivot_table` aggregates them | Raises an error |
unstack never aggregates. If the index has duplicate (store, month) pairs, it raises ValueError: Index contains duplicate entries, cannot reshape. In the example above, groupby(...).sum() removed the duplicates first, which is why unstack worked. A common pattern is groupby followed by unstack. It gives roughly the same result as pivot_table with aggfunc="sum".
When to prefer which
Use unstack when your data already has a meaningful index, such as the output of groupby. This avoids a reset_index followed by a pivot. Use pivot or melt when your keys are ordinary columns, because the arguments (index, columns, values) are explicit and easier to read.
Common mistakes
- Forgetting which level is moved. With no argument,
unstackmoves the last level, so the result depends on the order of yourgroupbykeys. - Expecting
unstackto sum duplicates. It does not, so aggregate first. - Leaving a column axis name behind. After
unstack, the columns have a name such asmonth. Setwide.columns.name = Noneif it gets in the way.
Exercise
Given indexed = sales.groupby(["store", "month"])["sales"].sum(), write one expression that gives a table with months as rows and stores as columns, with 0 in empty cells.
Show answer
indexed.unstack("store", fill_value=0). You can also write indexed.unstack(0, fill_value=0), because store is level 0. The store level moves into the columns. The month level stays in the index, so months become rows.