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

bookunstack()

Veeg om het menu te tonen

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

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 2. Hoofdstuk 3

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 2. Hoofdstuk 3
some-alt