Stack and Unstack
Learn how to apply stacking and unstacking methods on MultiIndex DataFrames.
We'll cover the following
Overview of stacking and unstacking
The pandas
methods stack()
and unstack()
are similar conceptually to pivot()
and melt()
. Given the similarity, when do we use stack()
and unstack()
? The two methods stack()
and unstack()
are primarily designed to be used on MultiIndex DataFrames, and allow us to reshape so that the indexes are modified at the row or column levels that we may specify.
That said, both stack()
and unstack()
can still be used for single-indexed DataFrames, although the use of pivot()
and melt()
is more mainstream and intuitive. To recap, a MultiIndex (also known as hierarchical-indexed) DataFrame is one with multiple columns acting as row identifiers or multiple rows acting as column identifiers.
Get hands-on with 1400+ tech skills courses.