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

bookstack()

Deslize para mostrar o 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.

123456789101112131415
import 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)
copy

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.

question mark

Which of the following best describes what the stack() method does to a DataFrame?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 31

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 1. Capítulo 31
some-alt