0
0
Pandasdata~5 mins

stack() and unstack() in Pandas

Choose your learning style9 modes available
Introduction

stack() and unstack() help change how data is arranged in tables. They make it easy to switch between wide and tall views of data.

You want to turn columns into rows to see data in a long list.
You want to turn rows into columns to compare data side by side.
You need to reshape data for charts or reports.
You want to clean up data after grouping or pivoting.
You want to prepare data for analysis by changing its shape.
Syntax
Pandas
DataFrame.stack(level=-1, dropna=True)

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

stack() moves the innermost column level to become the innermost row index.

unstack() moves the innermost row index level to become the innermost column.

Examples
Stacking a simple DataFrame turns columns into rows.
Pandas
import pandas as pd

data = {'A': {0: 1, 1: 2}, 'B': {0: 3, 1: 4}}
df = pd.DataFrame(data)

stacked = df.stack()
print(stacked)
Stacking on a specific column level moves that level to the row index.
Pandas
import pandas as pd

# DataFrame with MultiIndex columns
data = {('A', 'x'): {0: 1, 1: 2}, ('A', 'y'): {0: 3, 1: 4}, ('B', 'x'): {0: 5, 1: 6}}
df = pd.DataFrame(data)

stacked = df.stack(level=1)
print(stacked)
Unstacking a row level moves it to columns.
Pandas
import pandas as pd

# DataFrame with MultiIndex rows
data = {0: {('a', 'x'): 1, ('a', 'y'): 2, ('b', 'x'): 3}}
df = pd.DataFrame(data)

unstacked = df.unstack(level=1)
print(unstacked)
Stacking an empty DataFrame returns an empty Series.
Pandas
import pandas as pd

# Empty DataFrame
empty_df = pd.DataFrame()
print(empty_df.stack())
Sample Program

This program shows how to stack columns into rows and then unstack rows back into columns using a DataFrame with multi-level columns.

Pandas
import pandas as pd

# Create a DataFrame with MultiIndex columns
sales_data = {('Store', 'A'): {0: 100, 1: 150}, ('Store', 'B'): {0: 200, 1: 250}, ('Product', 'X'): {0: 10, 1: 15}, ('Product', 'Y'): {0: 20, 1: 25}}
df = pd.DataFrame(sales_data)

print("Original DataFrame:")
print(df)

# Stack the inner column level (level=1) to rows
stacked_df = df.stack(level=1)
print("\nDataFrame after stacking level 1 columns to rows:")
print(stacked_df)

# Unstack the last row index level to columns
unstacked_df = stacked_df.unstack(level=1)
print("\nDataFrame after unstacking the last row index level back to columns:")
print(unstacked_df)
OutputSuccess
Important Notes

Time complexity: Stacking and unstacking usually take O(n) time where n is the number of elements.

Space complexity: They create new objects, so space is O(n) as well.

Common mistake: Forgetting that stack() reduces columns and increases row levels, while unstack() does the opposite.

Use stack() when you want to make data longer (more rows). Use unstack() when you want to make data wider (more columns).

Summary

stack() moves columns into rows, making data longer.

unstack() moves rows into columns, making data wider.

They help reshape data for easier analysis and visualization.