unstack in python code example

Example 1: df unstack

>>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),
...                                    ('two', 'a'), ('two', 'b')])
>>> s = pd.Series(np.arange(1.0, 5.0), index=index)
>>> s
one  a   1.0
     b   2.0
two  a   3.0
     b   4.0
dtype: float64

s.unstack(level=-1)
     a   b
one  1.0  2.0
two  3.0  4.0

s.unstack(level=0)
   one  two
a  1.0   3.0
b  2.0   4.0

df = s.unstack(level=0)
df.unstack()
one  a  1.0
     b  2.0
two  a  3.0
     b  4.0
dtype: float64

Example 2: how to unstack multiindex pandas

import pandas as pd
import numpy as np
arrays = [['Monday','Monday','Tursday','Tursday'],
                        ['Morning','Noon','Morning','Evening']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['Weekday', 'Time'])
df = pd.DataFrame(np.random.randint(5, size=(4,2)), index=index)

In [39]: df
Out[39]: 
                 0  1
Weekday Time         
Monday  Morning  1  3
        Noon     2  1
Tursday Morning  3  3
        Evening  1  2

In [40]: pd.DataFrame(df.to_records())
Out[40]: 
   Weekday     Time  0  1
0   Monday  Morning  1  3
1   Monday     Noon  2  1
2  Tursday  Morning  3  3
3  Tursday  Evening  1  2