🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpandas

pandas Documentation

LOADING ENGINE...

df.unstack()

AI & DATA SCIENCE // df-unstack

df.unstack() pivots the innermost level of a DataFrame or Series's row index into a new innermost level of the columns, the exact inverse of stack().

Syntax

df.unstack(level=-1, fill_value=None)

Deep Dive Course

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.

editor.html
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())
localhost:3000

2Practical Example

Here is a real-world application of df.unstack() showing how it is used in production Pandas code.

editor.html
import pandas as pd

s = pd.Series([90, 85], index=pd.MultiIndex.from_tuples([("Alice", "math"), ("Bob", "science")]))
print(s.unstack(fill_value=0))
localhost:3000

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.

editor.html
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())
localhost:3000

Examples

Example 01Basic Usage
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())
Example 02Advanced Example
import pandas as pd

s = pd.Series([90, 85], index=pd.MultiIndex.from_tuples([("Alice", "math"), ("Bob", "science")]))
print(s.unstack(fill_value=0))

Best Practices

  • Use unstack() to convert a hierarchically-indexed Series or DataFrame into a wider, more spreadsheet-like layout for display or export
  • Pass fill_value when NaN isn't the right stand-in for combinations missing from the original taller data
  • 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

Interview Question

Why might df.unstack() produce NaN values in its result, and how would you avoid that if a specific default value makes more sense for your data?

Hint: Think about what happens for combinations of index levels that never actually occurred in the original data.

unstack() creates a cell for every combination of the remaining index level and the newly-created columns, but the original, taller data might not have had an entry for every such combination, like a specific person never having a score recorded for a specific subject. For those combinations that simply don't exist in the source data, unstack() fills the resulting cell with NaN, since there's no real value to put there. Passing fill_value to unstack() lets you substitute a more appropriate default, like 0, for exactly those missing combinations instead of leaving NaN.

Exercises

MediumPractice using df.unstack() in a real scenario.
View Solution
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())

Frequently Asked Questions

Why might df.unstack() produce NaN values in its result, and how would you avoid that if a specific default value makes more sense for your data?

unstack() creates a cell for every combination of the remaining index level and the newly-created columns, but the original, taller data might not have had an entry for every such combination, like a specific person never having a score recorded for a specific subject. For those combinations that simply don't exist in the source data, unstack() fills the resulting cell with NaN, since there's no real value to put there. Passing fill_value to unstack() lets you substitute a more appropriate default, like 0, for exactly those missing combinations instead of leaving NaN.

Related Functions

df-stackpd-multiindexdf-fillna