unstack() is most commonly applied to a Series or DataFrame with a hierarchical (MultiIndex) row index, taking the innermost index level's unique values and turning them into new columns, effectively widening the data — the exact mirror image of what stack() does. The level parameter controls which specific index level gets pivoted if there are more than two, and fill_value lets you specify what to put in place of the NaN that otherwise appears for any combination that didn't exist in the original, taller data.
1Understanding df.unstack()
unstack() is most commonly applied to a Series or DataFrame with a hierarchical (MultiIndex) row index, taking the innermost index level's unique values and turning them into new columns, effectively widening the data — the exact mirror image of what stack() does. The level parameter controls which specific index level gets pivoted if there are more than two, and fill_value lets you specify what to put in place of the NaN that otherwise appears for any combination that didn't exist in the original, taller data.
Pass fill_value=0, or another appropriate default, to unstack() when the widened result would otherwise contain NaN for combinations that simply didn't exist in the original data, and a specific default makes more sense in context than a missing-value marker.
import pandas as pd
s = pd.Series([90, 95, 85, 80], index=pd.MultiIndex.from_tuples([("Alice", "math"), ("Alice", "science"), ("Bob", "math"), ("Bob", "science")]))
print(s.unstack())2Practical Example
Here is a real-world application of df.unstack() showing how it is used in production Pandas code.
import pandas as pd
s = pd.Series([90, 85], index=pd.MultiIndex.from_tuples([("Alice", "math"), ("Bob", "science")]))
print(s.unstack(fill_value=0))3Best Practices
Follow these guidelines when working with df.unstack():
1. Use unstack() to convert a hierarchically-indexed Series or DataFrame into a wider, more spreadsheet-like layout for display or export
2. Pass fill_value when NaN isn't the right stand-in for combinations missing from the original taller data
3. Specify the level parameter explicitly when working with a MultiIndex that has more than two levels, rather than assuming the innermost level is always the one you want to unstack
Tip: Pass fill_value=0, or another appropriate default, to unstack() when the widened result would otherwise contain NaN for combinations that simply didn't exist in the original data, and a specific default makes more sense in context than a missing-value marker.
import pandas as pd
s = pd.Series([90, 95, 85, 80], index=pd.MultiIndex.from_tuples([("Alice", "math"), ("Alice", "science"), ("Bob", "math"), ("Bob", "science")]))
print(s.unstack())