0
0
Pandasdata~5 mins

stack() and unstack() in Pandas - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the stack() function do in pandas?

stack() moves the columns of a DataFrame into the row index, turning columns into a new level of the row index. It "compresses" the DataFrame horizontally into a Series with a MultiIndex.

Click to reveal answer
beginner
What is the purpose of the unstack() function in pandas?

unstack() does the opposite of stack(). It moves a level of the row index into columns, "widening" the DataFrame or Series back to a wider shape.

Click to reveal answer
intermediate
If you have a DataFrame with a MultiIndex on rows, how can you convert one index level into columns?

You can use unstack(level) where level is the index level you want to move to columns.

Click to reveal answer
beginner
What happens if you call stack() on a DataFrame with no missing values?

The DataFrame columns become a new inner level of the row index, and the data is returned as a Series with a MultiIndex.

Click to reveal answer
intermediate
How do stack() and unstack() help in reshaping data?

They help by changing the shape of data between 'wide' and 'long' formats, making it easier to analyze or visualize data depending on the task.

Click to reveal answer
What does stack() do to a DataFrame?
ASorts the DataFrame
BMoves rows into columns
CDeletes missing values
DMoves columns into the row index
Which function reverses the effect of stack()?
Aunstack()
Bgroupby()
Cmelt()
Dpivot()
If a DataFrame has a MultiIndex on rows, which method moves one index level to columns?
Areset_index()
Bstack()
Cunstack()
Dset_index()
What type of object does stack() return when applied to a DataFrame?
ADataFrame
BSeries with MultiIndex
CList
DDictionary
Why use stack() and unstack() in data analysis?
ATo reshape data between wide and long formats
BTo remove duplicates
CTo sort data alphabetically
DTo merge datasets
Explain in your own words what stack() does to a DataFrame and give a simple example.
Think about turning columns into rows.
You got /3 concepts.
    Describe how unstack() can be used to reshape data and why this might be useful.
    Consider the opposite of stacking.
    You got /3 concepts.