Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn unstack() | Reshaping Data
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
TRACK DA - PANDAS MODULE GEN

bookunstack()

Swipe to show menu

The unstack() method in pandas is a powerful tool for reshaping data, especially when working with DataFrames or Series that use a MultiIndex. You can use unstack() to pivot one of the row index levels into column labels, effectively reversing the transformation performed by stack(). This operation is particularly useful when you want to convert a long-form table (with multiple index levels) into a wide-form table (with columns for each unique value of a specific index level).

123456789101112
import pandas as pd # Create a Series with a MultiIndex index = pd.MultiIndex.from_tuples( [('A', 2022), ('A', 2023), ('B', 2022), ('B', 2023)], names=['company', 'year'] ) sales = pd.Series([100, 120, 90, 110], index=index, name="sales") # Unstack the 'year' level to columns df_unstacked = sales.unstack() print(df_unstacked)
copy

The level parameter in unstack() determines which index level will be moved from the row index into the columns. By default, unstack() will use the innermost index level, but you can specify any level by its name or integer position. This flexibility allows you to reshape your data in the way that best fits your analysis. For example:

  • Unstacking the outer index level creates columns for each unique value of that level, while keeping the remaining levels as the row index;
  • Unstacking the innermost index level (the default) pivots only that level to columns.

Always choose the level that matches your desired table structure for analysis.

question mark

What is the primary purpose of the unstack() method in pandas?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

SectionΒ 2. ChapterΒ 3
some-alt