0
0
PandasHow-ToBeginner · 3 min read

How to Use unstack in pandas: Syntax and Examples

In pandas, unstack() pivots a level of the row index into columns, transforming a stacked DataFrame into a wider format. You can specify which index level to unstack by passing its name or position to unstack(level).
📐

Syntax

The basic syntax of unstack() is:

  • DataFrame.unstack(level=-1, fill_value=None)

level: The index level to unstack. Defaults to the last level (-1).

fill_value: Value to replace missing values after unstacking. Defaults to None.

python
DataFrame.unstack(level=-1, fill_value=None)
💻

Example

This example shows how to use unstack() to pivot the last index level into columns.

python
import pandas as pd

# Create a sample DataFrame with a MultiIndex
index = pd.MultiIndex.from_tuples(
    [('A', 1), ('A', 2), ('B', 1), ('B', 2)],
    names=['letter', 'number']
)
data = pd.Series([10, 20, 30, 40], index=index)

# Unstack the last level ('number') to columns
unstacked = data.unstack()
print(unstacked)
Output
number 1 2 letter A 10 20 B 30 40
⚠️

Common Pitfalls

Common mistakes when using unstack() include:

  • Not having a MultiIndex on rows, which causes unstack() to fail.
  • Unstacking a level that does not exist, causing a KeyError.
  • Ignoring missing values created by unstacking, which can be handled with fill_value.

Always check your DataFrame's index before unstacking.

python
import pandas as pd

# Example of error when unstacking a non-existent level
s = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
try:
    s.unstack()
except Exception as e:
    print(f'Error: {e}')

# Correct way: create MultiIndex first
index = pd.MultiIndex.from_tuples([('a', 1), ('b', 2), ('c', 3)])
s = pd.Series([1, 2, 3], index=index)
print(s.unstack())
Output
Error: can not unstack a non-series 1 1.0 2 2.0 3 3.0 dtype: float64
📊

Quick Reference

ParameterDescription
levelIndex level to unstack (default last level)
fill_valueValue to replace missing values after unstacking
ReturnsDataFrame with specified index level moved to columns

Key Takeaways

Use unstack() to pivot a row index level into columns in a DataFrame.
Ensure your DataFrame has a MultiIndex before using unstack().
Specify the level to unstack by name or position for control.
Handle missing values after unstacking with the fill_value parameter.
Unstacking transforms data from long to wide format for easier analysis.