stack()
Swipe to show menu
Understanding how to manipulate the shape of your data is a key part of effective data analysis. The stack() method in pandas is a powerful tool for reshaping DataFrames, especially when you are working with multi-level indexes. By stacking, you can pivot the columns of your DataFrame into the row index, which is especially useful when you want to move from a wide format to a long format. This operation creates a multi-level (hierarchical) index on the rows, making it easier to work with data that has multiple dimensions or categories.
123456789101112131415import pandas as pd # Create a simple DataFrame with multiple columns df = pd.DataFrame({ "A": [1, 2], "B": [3, 4] }, index=["X", "Y"]) # Stack the DataFrame stacked = df.stack() print("Original DataFrame:") print(df) print("\nStacked Series with MultiIndex:") print(stacked)
When you use stack(), each column in your DataFrame is pivoted into the row index, resulting in a Series with a MultiIndex. The first level of the index is the original row index, and the second level is formed from the column labels. This is particularly useful when you want to transform data for hierarchical analysis or when preparing data for certain types of visualizations. You should use stack() when you need to convert columns into a deeper row index, especially in preparation for further reshaping or aggregation operations.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat