Reshaping :
Stack
import numpy as np
import pandas as pd
tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
'foo', 'foo'],
['one', 'two', 'one', 'two',
'one', 'two']]))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(6, 2), index=index, columns=['M', 'N'])
df2 = df[:4]
df2
The stack() method “compresses” a level in the DataFrame’s columns.
stacked = df2.stack()
stacked
stacked.unstack()
stacked.unstack(1)
stacked.unstack(0)
Pivot tables
df = pd.DataFrame({'M': ['one', 'one', 'two', 'three'] * 2,
'N': ['A', 'B'] * 4,
'O': ['foo', 'foo', 'bar', 'bar'] * 2,
'P': np.random.randn(8),
'Q': np.random.randn(8)})
df
You can produce pivot tables from this data very easily:
pd.pivot_table(df, values='P', index=['M', 'N'], columns=['O'])