The stack() function

When stacking, a set of column labels get converted to an index level. To explore stacking further, let's use a DataFrame with a MultiIndex along the row-index and column-index:

multi_df = sales_data[["Sales", "Quantity", "Category", "ShipMode"]].groupby(["Category", "ShipMode"]).agg([np.sum, np.mean])multi_df

The following will be the output:

Hierarchical data for stacking and unstacking

Applying stack() makes a wide DataFrame longer. Let's apply stack() on the preceding DataFrame. The column labels on the last level get added to the MultiIndex:


The following will be the output:

Result of stacking

Get Mastering pandas - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.