0
0
Pandasdata~10 mins

stack() and unstack() in Pandas - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - stack() and unstack()
Start with DataFrame
Call stack()
Stacked Series with MultiIndex
Call unstack()
Original or reshaped DataFrame
stack() turns columns into rows creating a MultiIndex Series; unstack() reverses this by turning row levels back into columns.
Execution Sample
Pandas
import pandas as pd

df = pd.DataFrame({
  'A': [1, 2],
  'B': [3, 4]
})
stacked = df.stack()
unstacked = stacked.unstack()
This code creates a DataFrame, stacks it to turn columns into rows, then unstacks it back to the original shape.
Execution Table
StepActionData StructureShape/IndexOutput Preview
1Create DataFrame dfDataFrame(2 rows, 2 columns) A B 0 1 3 1 2 4
2Call df.stack()Series with MultiIndex(4 rows)0 A 1 B 3 1 A 2 B 4
3Call stacked.unstack()DataFrame(2 rows, 2 columns) A B 0 1 3 1 2 4
4End--stack() and unstack() complete, DataFrame restored
💡 All steps executed; stack() converted columns to rows, unstack() reversed it.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
dfNoneDataFrame(2x2)DataFrame(2x2)DataFrame(2x2)DataFrame(2x2)
stackedNoneNoneSeries with MultiIndex(4)Series with MultiIndex(4)Series with MultiIndex(4)
unstackedNoneNoneNoneDataFrame(2x2)DataFrame(2x2)
Key Moments - 3 Insights
Why does stack() result in a Series with a MultiIndex instead of a DataFrame?
stack() compresses columns into a single row index level, creating a Series with a MultiIndex to keep track of original row and column labels, as shown in execution_table step 2.
What happens if you call unstack() on a Series without a MultiIndex?
unstack() requires a MultiIndex to pivot one level back to columns. Without it, unstack() will raise an error or not reshape properly, unlike the successful unstack in step 3.
Does unstack() always restore the original DataFrame shape?
If no data is lost or filtered, unstack() reverses stack() perfectly, restoring the original shape as in step 3. But if data is missing or filtered, the shape may differ.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 2. What is the shape of the stacked data?
A4 rows, single column Series with MultiIndex
B2 rows, 2 columns DataFrame
C4 rows, 2 columns DataFrame
D2 rows, single column Series
💡 Hint
Refer to the 'Shape/Index' and 'Data Structure' columns in step 2 of the execution table.
At which step does the data return to its original DataFrame shape?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Check the 'Shape/Index' and 'Output Preview' columns for step 3 in the execution table.
If the original DataFrame had 3 columns instead of 2, how would the stacked Series length change at step 2?
AIt would have 3 rows
BIt would have 6 rows
CIt would remain 4 rows
DIt would have 9 rows
💡 Hint
Stacking multiplies rows by columns; see variable_tracker for how shape changes.
Concept Snapshot
stack(): Converts DataFrame columns into rows, creating a Series with MultiIndex.
unstack(): Reverses stack(), turning MultiIndex rows back into columns.
Use stack() to reshape wide data to long format.
Use unstack() to reshape long data back to wide.
Both preserve data labels via MultiIndex.
Common in data cleaning and reshaping tasks.
Full Transcript
This visual execution shows how pandas stack() and unstack() work. Starting with a DataFrame of 2 rows and 2 columns, stack() compresses columns into rows, creating a Series with a MultiIndex that tracks original row and column labels. Then unstack() reverses this operation, restoring the original DataFrame shape. The execution table traces each step with data structure type, shape, and output preview. Variable tracker shows how variables df, stacked, and unstacked change. Key moments clarify common confusions about MultiIndex and shape restoration. The quiz tests understanding of shapes and transformations. This helps beginners see exactly how stack and unstack reshape data step-by-step.