unstack()
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).
123456789101112import 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)
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.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat