Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen unstack() | s1
Practice
Projects
Quizzes & Challenges
Quizze
Challenges
/
Track DA with Py - Data Manipulation with pandas

bookunstack()

Swipe um das Menü anzuzeigen

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

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 32

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 32
some-alt