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.
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.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
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
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
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
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 the unstack() examples interactively directly in your browser:
Reference: Pandas unstack() documentation.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.