Pandas: Pivot MultiIndex Rows to Columns with unstack()

Pivot row MultiIndex levels into column headers using the Pandas unstack() method. Convert stacked or long multi-index datasets into wide-format DataFrames for easy comparison and presentation.

Introduction to unstack() 🔝

The unstack() method is the inverse of stack(). It pivots a level of a row MultiIndex into a new column axis, expanding long-format structured data back into a wide-format representation.

Create MultiIndex row dataset 🔝

Let us start with a long multi-index DataFrame indexed by student name and exam term.
import pandas as pd
idx = pd.MultiIndex.from_tuples([("Ravi", "Term1"), ("Ravi", "Term2"), ("Raju", "Term1"), ("Raju", "Term2")], names=["NAME", "TERM"])
df = pd.DataFrame({"MATH": [85, 90, 88, 92], "ENGLISH": [78, 82, 80, 85]}, index=idx)
print(df)
assert df.index.nlevels == 2

Expected output

            MATH  ENGLISH
NAME TERM                
Ravi Term1    85       78
     Term2    90       82
Raju Term1    88       80
     Term2    92       85

Basic unstack operation 🔝

By default, unstack() pivots the innermost row index level (level=-1, which is TERM) into column headers.
unstacked = df.unstack()
print(unstacked)
assert unstacked.columns.nlevels == 2

Expected output

      MATH        ENGLISH      
TERM Term1 Term2    Term1 Term2
NAME                           
Raju    88    92       80    85
Ravi    85    90       78    82

Unstacking specific levels 🔝

Unstack outer level 0 (NAME) or refer to level names directly using level="NAME".
unstacked_name = df.unstack(level="NAME")
print(unstacked_name)
assert "Ravi" in unstacked_name.columns.get_level_values(1)

Expected output

      MATH      ENGLISH     
NAME  Raju Ravi    Raju Ravi
TERM                        
Term1   88   85      80   78
Term2   92   90      85   82

Filling missing values with fill_value 🔝

When unstacking creates missing combinations across index levels, pass fill_value=0 to replace NaN values automatically.
sparse_idx = pd.MultiIndex.from_tuples([("Ravi", "Term1"), ("Raju", "Term2")], names=["NAME", "TERM"])
sparse_df = pd.DataFrame({"MATH": [85, 92]}, index=sparse_idx)
filled = sparse_df.unstack(fill_value=0)
print(filled)
assert filled.loc["Ravi", ("MATH", "Term2")] == 0

Expected output

      MATH      
TERM Term1 Term2
NAME            
Raju     0    92
Ravi    85     0

Exercise: unstack student marks 🔝

Create a MultiIndex Series with student names (Ravi, Raju) and subjects (Math, Science). Unstack the subject level to convert it into a wide DataFrame. Verify that columns contain Math and Science.

Exercise solution 🔝

Solution building the MultiIndex Series and applying unstack().
ex_idx = pd.MultiIndex.from_tuples([("Ravi", "Math"), ("Ravi", "Science"), ("Raju", "Math"), ("Raju", "Science")])
ex_s = pd.Series([90, 95, 80, 85], index=ex_idx)
answer = ex_s.unstack()
print(answer)
assert list(answer.columns) == ["Math", "Science"]

Expected output

      Math  Science
Ravi    90       95
Raju    80       85

Practice in Google Colab 🔝

Interactive Colab Notebook

Practice the unstack() examples interactively directly in your browser:

Open In Colab View on GitHub

Reference: Pandas unstack() documentation.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer