
The unstack() method in pandas converts the specified row levels to column levels. This is the opposite of stack() method.
syntax –
DataFrame.unstack(level=- 1, fill_value=None)
level – The integer index or name(s) of the row level to convert into a column level. By default, level=-1
, which means that the inner-most row level is converted.
fill_value – Replace NaN with this value if the unstack produces missing values.
Examples –
1 . Unstacking a DataFrames with Single-Level Index –
Let’s create a dataframe that has single level rows.
df = pd.DataFrame([[60, 5],[70, 6],[50, 4]],
index=['Max','Steve','Dustin'],
columns=['Weight','Height'])
df

Calling unstack on this dataframe will create a multi-level index.
df.unstack()

2 . Unstacking a DataFrame with Multi-Level Index –
index = [('A', 'Max'), ('A','Steve'),
('B','Dustin'), ('B','Lucas')]
multi_index = pd.MultiIndex.from_tuples(index)
df = pd.DataFrame({'Weight':[60, 70, 50, 55],
'height':[5, 6, 4, 5]},
index=multi_index)
df

By Default the Level= -1 which means the innermost level [Max, steve, Dustin, Lucas] will be converted to columns.
df.unstack()

The outermost index [A, B] is called the level 0. The index after that [Max, Steve, Dustin, Lucas] is called level 1. The index after that is called level 2. So, for example if we want to convert the outermost index [A, B] to columns then we need to pass level=0.
df.unstack(level=0)

3 . Fill Value –
To fill NaN values with some other values use the fill_value parameter.
By Default when fill_value=None –
df.unstack()

When fill_value has some other values –
df.unstack(fill_value=0)
