Reshape using Stack() and unstack() function in Pandas python

Reshape using Stack() and unstack() function in Pandas python: Reshaping the data using stack() function in pandas converts the data into stacked format .i.e. the column is stacked row wise. When more than one column header is present we can stack the specific column header by specified the level. unstack() function in pandas converts the data into unstacked format. Let’s see with an example.

Stack a dataframe

Reshape using Stack and unstack function in Pandas python 0

  • Stacking a dataframe at level 1 will stack maths and science columns row wise
  • Stacking a dataframe at level 0 will stack semester1 and semester2 columns row wise.

 

Unstack a dataframe

Reshape using Stack and unstack function in Pandas python 00

  • Unstack is simply the reverse of stack

 

Create multiple header dataframe:


import pandas as pd
import numpy as np


header = pd.MultiIndex.from_product([['Semester1','Semester2'],['Maths','Science']])
d=([[12,45,67,56],[78,89,45,67],[45,67,89,90],[67,44,56,55]])


df = pd.DataFrame(d,
                  index=['Alisa','Bobby','Cathrine','Jack'],
                  columns=header)
df

The resultant multiple header dataframe will be

Reshape using Stack and unstack function in Pandas python 1

Stack the dataframe:

Stack() Function in dataframe stacks the column to rows at level 1 (default).

# stack the dataframe


stacked_df=df.stack()
stacked_df

so the stacked dataframe will be

Reshape using Stack and unstack function in Pandas python 2

 

Unstack the dataframe:

unstack() Function in dataframe unstacks the row to columns . Basically it’s a reverse of stacking


# unstack the dataframe
unstacked_df = stacked_df.unstack()
unstacked_df

so the resultant unstacked dataframe will be

Reshape using Stack and unstack function in Pandas python 3

 

Stack the dataframe at level 0:

Stack() Function with level 0 argument stacks the column semester.

# stack the dataframe of column at level 0

stacked_df_lvl=df.stack(level=0)
stacked_df_lvl

so the level 0 stacked dataframe will be

Reshape using Stack and unstack function in Pandas python 4

 

 

unstack the dataframe :


# unstack the dataframe
unstacked_df1 = stacked_df_lvl.unstack()
unstacked_df1

so the resultant unstacked dataframe will be

Reshape using Stack and unstack function in Pandas python 5

 

previous-small Reshape using Stack and unstack function in Pandas python                                                                                                         next_small Reshape using Stack and unstack function in Pandas python

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts