stack() and unstack() (Pandas)

stack() moves a DataFrame's columns down into the row index, making the data taller and narrower; unstack() does the reverse, pivoting an index level up into columns. They reshape between wide and long forms.

Pandas

stack moves one or more column levels into inner row-index levels. With a single column level the result is a Series; unstack moves a row-index level into columns. These operations change layout, and a round trip can also change ordering, dtype or missing combinations.

Pandas 3 uses the newer stack implementation by default. It retains existing missing values and requires the legacy dropna and sort arguments to remain unspecified. Older defaults commonly dropped missing values; do not copy stack(dropna=False) into current code without checking the installed version.

Choose levels by name or position. unstack requires unique combinations of the remaining and moved labels; duplicate combinations cannot fit into one cell without an aggregation policy. For the complete, uniquely labeled example below, the round trip preserves the original table.

Syntax

df.stack(level=-1)  |  df.unstack(level=-1)

Examples

Python

import pandas as pd
frame = pd.DataFrame({"a": [1, 2], "b": [3, 4]}, index=["x", "y"])
stacked = frame.stack()
print(stacked.index.tolist())
print(stacked.tolist())
print(stacked.unstack().equals(frame))

Output:

[('x', 'a'), ('x', 'b'), ('y', 'a'), ('y', 'b')]
[1, 3, 2, 4]
True

Learn it in a lesson

See also

Back to the Dictionary