0
0
Pandasdata~20 mins

stack() and unstack() in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Stack and Unstack Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of stacking a DataFrame with MultiIndex columns?
Given the following DataFrame, what will be the result of df.stack()?
Pandas
import pandas as pd

cols = pd.MultiIndex.from_tuples([('A', 'one'), ('A', 'two'), ('B', 'one'), ('B', 'two')])
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
df = pd.DataFrame(data, columns=cols)
result = df.stack()
A
A  one  0    1
          1    5
   two  0    2
          1    6
B  one  0    3
          1    7
   two  0    4
          1    8
dtype: int64
B
0  A  one    1
      two    2
   B  one    3
      two    4
1  A  one    5
      two    6
   B  one    7
      two    8
dtype: int64
C
A    one  0    1
           1    5
     two  0    2
           1    6
B    one  0    3
           1    7
     two  0    4
           1    8
dtype: int64
D{0: {('A', 'one'): 1, ('A', 'two'): 2, ('B', 'one'): 3, ('B', 'two'): 4}, 1: {('A', 'one'): 5, ('A', 'two'): 6, ('B', 'one'): 7, ('B', 'two'): 8}}
Attempts:
2 left
💡 Hint
stack() moves the innermost column level to become the innermost row index level.
data_output
intermediate
1:30remaining
What is the shape of the DataFrame after unstacking a Series with MultiIndex?
Consider a Series with MultiIndex of two levels and 6 elements. After applying unstack() on the inner level, what will be the shape of the resulting DataFrame?
Pandas
import pandas as pd

index = pd.MultiIndex.from_tuples([('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)])
data = pd.Series(range(6), index=index)
result = data.unstack()
A(6, 1)
B(3, 2)
C(1, 6)
D(2, 3)
Attempts:
2 left
💡 Hint
unstack() pivots the inner index level to columns.
🔧 Debug
advanced
1:30remaining
Why does this unstack() call raise a KeyError?
Given the DataFrame below, why does df.unstack(level=2) raise a KeyError?
Pandas
import pandas as pd

index = pd.MultiIndex.from_tuples([(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')], names=['num', 'char'])
df = pd.DataFrame({'value': [10, 20, 30, 40]}, index=index)
result = df.unstack(level=2)
AKeyError because the DataFrame is empty.
BKeyError because the DataFrame has no columns to unstack.
CKeyError because unstack() requires a column MultiIndex, not row MultiIndex.
DKeyError because level 2 does not exist in the index; only levels 0 and 1 exist.
Attempts:
2 left
💡 Hint
Check the number of levels in the DataFrame's index.
🚀 Application
advanced
2:00remaining
Transform a DataFrame with stacked sales data back to wide format
You have a DataFrame with sales data stacked by 'Store' and 'Product' as row indices and 'Month' as columns. Which code correctly unstacks the 'Product' level to columns?
Pandas
import pandas as pd

index = pd.MultiIndex.from_tuples([('Store1', 'ProdA'), ('Store1', 'ProdB'), ('Store2', 'ProdA'), ('Store2', 'ProdB')], names=['Store', 'Product'])
data = pd.DataFrame({'Jan': [100, 150, 200, 250], 'Feb': [110, 160, 210, 260]}, index=index)

# Which code unstacks 'Product' to columns?
Adata.stack(level='Store')
Bdata.stack(level='Product')
Cdata.unstack(level='Product')
Ddata.unstack(level='Store')
Attempts:
2 left
💡 Hint
unstack moves a row index level to columns.
🧠 Conceptual
expert
2:30remaining
Understanding the effect of stack() and unstack() on DataFrame shape
If a DataFrame has shape (4, 3) with a simple index and columns, what will be the shape after applying stack() and then unstack()?
AAfter stack(): (12,), after unstack(): (4, 3)
BAfter stack(): (4, 3), after unstack(): (12,)
CAfter stack(): (3, 4), after unstack(): (4, 3)
DAfter stack(): (12, 1), after unstack(): (3, 4)
Attempts:
2 left
💡 Hint
stack() converts columns into a new inner row index level, unstack() reverses this.