Sub topic 11
Moving index levels with stack and unstack
What this chapter covers
melt and pivot work on ordinary columns. stack and unstack work on index levels instead. They move a level between the row index and the column labels, and they are the tools underneath many groupby results and pivot_table outputs.
This chapter assumes you know groupby, set_index, and what a MultiIndex is (an index with more than one level). It also assumes you have read the earlier chapters on pivot and pivot_table.
The mental model
A DataFrame has two label axes: the row index and the column labels. Either axis can have several levels. Two methods move a level from one axis to the other:
unstackmoves a row index level into the columns. The data gets wider.stackmoves a column level into the row index. The data gets longer.
The values do not change. Only their labels move, which is why the pair is exactly reversible when no cells are missing.
unstack: index level to columns
The groupby result below has a two-level index. unstack("month") turns the month level 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)
wide = indexed.unstack("month")
print(wide)The grouped Series has three entries: A/jan is 100, B/feb is 90, and B/jan is 80. The unstacked table has the columns feb and jan, in sorted order. Store A has no february row, so that cell is NaN.
Three details matter here:
- The new column labels are sorted.
unstacksorts the values of the level it moves. That is whyfebcomes beforejan. - Missing combinations become NaN. Integer columns that receive a
NaNare converted to float, so the sales values print as100.0. - The default level is the last one.
unstack()with no argument moves the innermost index level. You can pass a level name, a position such as-1or0, or a list of levels.
Prefer level names to positions. Positions break silently when someone adds a level to the index.
Filling missing cells
unstack takes a fill_value argument. It replaces the cells created by missing combinations, and it keeps integer columns as integers.
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()
wide0 = indexed.unstack("month", fill_value=0)
print(wide0)
print(wide0.dtypes)Choose the fill value with care. A zero is right for "no sales happened", but wrong for "we do not know". If the distinction matters, leave the NaN in place.
stack: columns to index level
stack goes the other way. It takes the column labels and appends them as the innermost level of the row index. The result is a Series when the columns had a single level.
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
wide0 = sales.groupby(["store", "month"])["sales"].sum().unstack("month", fill_value=0)
long = wide0.stack()
print(long)
print(long.reset_index(name="sales"))Because wide0 had a column axis named month, the stacked Series has the index levels store and month. Calling reset_index(name="sales") turns the Series into a long DataFrame with the columns store, month and sales. The name argument supplies the column name for the values. Without it, the values land in a column called 0.
Unlike unstack, stack does not sort. The labels are emitted in the order the columns appear.
Using stack as a lightweight melt
If your identifier columns are already the index, stack does the same job as melt.
import pandas as pd
wide = pd.DataFrame({
"store": ["A", "B"],
"jan": [100, 80],
"feb": [110, 90],
})
long = (
wide.set_index("store")
.rename_axis(columns="month")
.stack()
.rename("sales")
.reset_index()
)
print(long)Here set_index("store") makes the identifier the index. rename_axis(columns="month") names the column axis, so the new index level is called month and not left blank. rename("sales") names the values. The result has four rows in the order A/jan, A/feb, B/jan, B/feb, and matches wide.melt(id_vars="store", var_name="month", value_name="sales") except for the row order. melt lists all of the first column before the second, so its order is A/jan, B/jan, A/feb, B/feb.
Working with three or more levels
With a deeper index you choose which level moves. The other levels stay in the row index.
import pandas as pd
data = pd.DataFrame({
"region": ["N", "N", "N", "N", "S", "S"],
"store": ["A", "A", "B", "B", "C", "C"],
"month": ["jan", "feb", "jan", "feb", "jan", "feb"],
"sales": [100, 110, 80, 90, 70, 75],
}).set_index(["region", "store", "month"])["sales"]
print(data.unstack()) # moves month, the last level
print(data.unstack("store")) # moves store
print(data.unstack("store", fill_value=0))
print(data.unstack(["store", "month"]))Read the four results this way:
data.unstack()gives rows of(region, store)and the columnsfebandjan.data.unstack("store")gives rows of(region, month)and one column per store. Region N has no store C and region S has no stores A or B, so many cells areNaN. The second call withfill_value=0removes them.data.unstack(["store", "month"])leaves onlyregionas the row index. The columns become a two-level MultiIndex of(store, month).
When you unstack several levels, you get MultiIndex columns. Flatten them the same way as in the earlier chapter, with ["_".join(map(str, col)) for col in df.columns].
Stacking MultiIndex columns
A DataFrame with MultiIndex columns, such as the output of pivot_table with aggfunc=["sum", "count"], can be stacked one level at a time. Pass the level name or number: multi.stack("month") moves the month level down and leaves the aggregation names as columns. This is a quick way to get from a wide, two-level report to a tidier layout without flattening.
Errors and edge cases
Duplicate index entries
unstack needs each combination of the remaining index levels and the moved level to be unique. This is the same restriction pivot has, and the error is also a ValueError.
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
try:
sales.set_index(["store", "month"])["sales"].unstack("month")
except ValueError as err:
print("unstack failed:", err)The message is "Index contains duplicate entries, cannot reshape". The fix is to aggregate first, as the groupby(...).sum() step above does, or to use pivot_table, which aggregates for you.
NaN handling in stack depends on the pandas version
The classic stack drops rows whose values are all NaN. Newer pandas has a rewritten implementation, available as stack(future_stack=True) from pandas 2.1 and the default in pandas 3.0. It keeps those rows and also no longer sorts the result in surprising ways for MultiIndex columns.
The round trip is only exact for complete data
df.unstack().stack() returns the original only when every combination exists and no cell is NaN. If the unstack created filler cells, the stack gives them back as extra rows, or silently drops them in the classic implementation.
Choosing between the tools
| Situation | Best tool |
|---|---|
| Identifiers are ordinary columns and you want long data | `melt` |
| Identifiers are already in the index | `stack` |
| Long data with unique keys goes to wide | `pivot` or `unstack` |
| Long data with duplicate keys goes to wide | `pivot_table`, or `groupby` then `unstack` |
| You need to move one level of a deep index | `unstack(level)` |
pivot is built on the same machinery as unstack. It sets the index and then unstacks. The practical difference is where your keys live: columns for pivot, index levels for unstack.
Summary
unstackmoves an index level into the columns, sorts the new labels, and createsNaNfor missing combinations.stackmoves a column level into the row index and keeps the column order.- Use level names,
fill_value, andreset_index(name=...)to keep the results explicit. - Duplicate entries raise a
ValueError, so aggregate first. - NaN handling in
stackdepends on the pandas version.
Exercise
You have s = df.groupby(["region", "store", "month"])["sales"].sum(). Write the call that gives one row per (region, month) and one column per store, with missing cells as 0 and integer values preserved.
Show answer
s.unstack("store", fill_value=0). The store level moves into the columns, and the remaining levels region and month stay in the row index. fill_value=0 fills the missing combinations without converting the integers to floats.
Exercise
A colleague runs df.set_index(["store", "month"])["sales"].unstack("month") and gets "Index contains duplicate entries, cannot reshape". Give two ways to fix it and say which one you would pick if the duplicates should be added together.
Show answer
Aggregate first with df.groupby(["store", "month"])["sales"].sum().unstack("month"), or use df.pivot_table(index="store", columns="month", values="sales", aggfunc="sum"). Both sum the duplicates, so either works. pivot_table is shorter and also offers fill_value and margins, so it is the better pick when you want a finished report.