What if you could flip your data table like a pancake to see hidden patterns instantly?
Why Stack and unstack in Data Analysis Python? - Purpose & Use Cases
Imagine you have a big table of sales data with many columns for different months. You want to compare sales month by month, but the table is wide and hard to read. You try to write down each month's data separately to analyze it.
Writing down or copying each month's data manually is slow and tiring. You might make mistakes copying numbers or lose track of which month belongs where. It is hard to see patterns or do calculations quickly when data is spread out in many columns.
Stack and unstack let you change the shape of your data easily. Stacking turns columns into rows, making the data longer and easier to compare. Unstacking does the opposite, turning rows back into columns. This helps you organize data the way you want without errors or extra work.
sales_jan = df['Jan'] sales_feb = df['Feb'] # Repeat for each month
stacked = df.stack() unstacked = stacked.unstack()
It makes reshaping data simple so you can explore and analyze it from different angles quickly and safely.
A store manager wants to see monthly sales trends easily. Using stack, they turn monthly columns into rows to plot sales over time. Then they unstack to get back the original table for reports.
Manual reshaping of data is slow and error-prone.
Stack and unstack let you switch between wide and long data formats easily.
This helps you analyze and visualize data more effectively.
Practice
stack() method do to a DataFrame in pandas?Solution
Step 1: Understand the stack operation
Thestack()method compresses columns into a single column, turning columns into rows.Step 2: Compare with unstack
Unlikeunstack(), which moves rows to columns,stack()makes data longer by stacking columns.Final Answer:
It moves columns into rows, making the data longer. -> Option AQuick Check:
Stack = columns to rows [OK]
- Confusing stack with unstack direction
- Thinking stack sorts data
- Assuming stack removes duplicates
df?Solution
Step 1: Recall unstack syntax
Theunstack()method by default unstacks the last level of the index, andlevel=-1explicitly specifies this.Step 2: Differentiate from stack
stack()is the opposite operation, so options A and B are incorrect.unstack()does not take anaxisparameter, so df.unstack(axis=1) is invalid.Final Answer:
df.unstack(level=-1) -> Option CQuick Check:
Unstack last level = df.unstack(level=-1) [OK]
- Using stack instead of unstack
- Passing axis parameter to unstack
- Not specifying level when needed
df below:import pandas as pd
d = {('A', 'x'): 1, ('A', 'y'): 2, ('B', 'x'): 3, ('B', 'y'): 4}
df = pd.Series(d).unstack()What is the output of
df.stack()?Solution
Step 1: Understand the initial DataFrame
Theunstack()converts the Series with MultiIndex into a DataFrame with columns 'x' and 'y' and index 'A' and 'B'.Step 2: Apply
Callingstack()on the DataFramestack()moves the columns 'x' and 'y' back into the inner level of the row index, producing a Series with MultiIndex.Final Answer:
A Series with MultiIndex where second level is stacked into rows -> Option BQuick Check:
Stack reverses unstack, making columns into row index [OK]
- Expecting a DataFrame output instead of Series
- Confusing which index level is stacked
- Thinking stack causes error here
df = pd.DataFrame({
'A': [1, 2],
'B': [3, 4]
})
stacked = df.stack(level=1)What is the cause of the error?
Solution
Step 1: Check DataFrame columns
The DataFrame has simple columns 'A' and 'B', which are not a MultiIndex, so specifyinglevel=1is invalid.Step 2: Understand stack level parameter
Thelevelparameter instack()refers to the level of the columns MultiIndex to stack. Without MultiIndex columns, level=1 causes an error.Final Answer:
DataFrame columns have no MultiIndex, so level=1 is invalid. -> Option DQuick Check:
Stack level requires MultiIndex columns [OK]
- Assuming stack only works on Series
- Thinking stack requires numeric data
- Ignoring the column index type
df with a MultiIndex on rows (levels: 'City', 'Year') and columns as years (e.g., 2020, 2021). You want to reshape it so that the 'Year' level from rows becomes columns, and the columns years become a new row level. Which sequence of operations correctly achieves this?Solution
Step 1: Unstack the 'Year' level from rows
Unstacking the 'Year' level moves it from the row index to columns, widening the DataFrame.Step 2: Stack the columns
Stacking the columns moves the columns years into a new row index level, making the data longer again but reshaped as desired.Final Answer:
First unstack the 'Year' level from rows, then stack the columns. -> Option AQuick Check:
Unstack rows then stack columns reshapes MultiIndex correctly [OK]
- Stacking before unstacking causes wrong shape
- Unstacking wrong index level
- Ignoring the need to reshape both rows and columns
Ready to prove it?
Pass the test and this pattern moves unknown
