In [1]:
'''
LESSION 5

- Stack/Unstack/Transpose functions
'''
# Import libraries
import pandas as pd
import sys
print('Python version ' + sys.version)
print('Pandas version: ' + pd.__version__)


Python version 2.7.13 |Anaconda 4.3.0 (64-bit)| (default, Dec 19 2016, 13:29:36) [MSC v.1500 64 bit (AMD64)]
Pandas version: 0.19.2

In [2]:
# Our small data set
d = {'one':[1,1],'two':[2,2]}
i = ['a','b']

# Create dataframe
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([u'a', u'b'], dtype='object')

In [5]:
# Bring the columns and place them in the index
stack = df.stack()
stack


Out[5]:
a  one    1
   two    2
b  one    1
   two    2
dtype: int64

In [6]:
# The index now includes the column names
stack.index


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

In [8]:
unstack = df.unstack()
unstack


Out[8]:
one  a    1
     b    1
two  a    2
     b    2
dtype: int64

In [9]:
unstack.index


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

In [10]:
transpose = df.T
transpose


Out[10]:
a b
one 1 1
two 2 2

In [11]:
transpose.index


Out[11]:
Index([u'one', u'two'], dtype='object')