Stack - Unstack - Transpose Functions Python Pandas Module

Author: Al-mamun Sarkar Date: 2020-04-01 17:14:31

Stack - Unstack - Transpose Functions Python Pandas Module. The following shows how to stack, unstack, transpose DataFrame using pandas module.

 

In [1]:

import pandas as pd

 

In [2]:

d = {'one':[1, 1], 'two':[2, 2]}
i = ['a', 'b']

df = pd.DataFrame(data=d, index=i)
df

Out[2]:

  one two
a 1 2
b 1 2

 

In [3]:

df.index

Out[3]:

Index(['a', 'b'], dtype='object')

 

Bring the columns and place them in the index:

In [4]:

stack = df.stack()
stack

Out[4]:

a  one    1
   two    2
b  one    1
   two    2
dtype: int64

 

In [5]:

stack.index

Out[5]:

MultiIndex(levels=[['a', 'b'], ['one', 'two']],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]])

 

In [6]:

unstack = df.unstack()
unstack

Out[6]:

one  a    1
     b    1
two  a    2
     b    2
dtype: int64

 

In [7]:

unstack.index

Out[7]:

MultiIndex(levels=[['one', 'two'], ['a', 'b']],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]])

 

T (transpose) function:

In [8]:

transpose = df.T
transpose

Out[8]:

  a b
one 1 1
two 2 2

 

In [9]:

transpose.index

Out[9]:

Index(['one', 'two'], dtype='object')