Stack and Unstack in Pandas


In [ ]:
import numpy as np
import pandas as pd

Create a series with a 3 level deep multi-index


In [ ]:
df = pd.DataFrame(data=np.random.rand(6,3), columns=['A','B','C'])

In [ ]:
df

In [ ]:
values = df.stack()
values

In [ ]:
values.name = 'values'

In [ ]:
values

In [ ]:
df2 = pd.DataFrame(values)
df2

In [ ]:
df2['id'] = range(df2.shape[0])
df2.head()

Unstacking the levels of a multi index


In [ ]:
df3 = df2.stack()
df3.head()

In [ ]:
df3.loc[0,'A','values']

In [ ]:
df3.unstack(0)

In [ ]:
df3.unstack(1)

In [ ]:
df3.unstack(2)

In [ ]:
df3.head()

Multi level index on columns


In [ ]:
df3.unstack().unstack()

In [ ]: