Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära unstack() | s1
Track DA with Py - Data Manipulation with pandas

bookunstack()

Svep för att visa menyn

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

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 32

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 1. Kapitel 32
some-alt