.. currentmodule:: pandas .. ipython:: python :suppress: import numpy as np import pandas as pd import os np.random.seed(123456) np.set_printoptions(precision=4, suppress=True) import matplotlib matplotlib.style.use('ggplot') import matplotlib.pyplot as plt pd.options.display.max_rows = 8 Reshaping --------- See the sections on :ref:`Hierarchical Indexing ` and :ref:`Reshaping `. Stack ~~~~~ .. ipython:: python tuples = list(zip(*[['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']])) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=['A', 'B']) df2 = df[:4] df2 The :meth:`~DataFrame.stack` method "compresses" a level in the DataFrame's columns. .. ipython:: python stacked = df2.stack() stacked With a "stacked" DataFrame or Series (having a ``MultiIndex`` as the ``index``), the inverse operation of :meth:`~DataFrame.stack` is :meth:`~DataFrame.unstack`, which by default unstacks the **last level**: .. ipython:: python stacked.unstack() stacked.unstack(1) stacked.unstack(0) Pivot Tables ~~~~~~~~~~~~ See the section on :ref:`Pivot Tables `. .. ipython:: python df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 3, 'B' : ['A', 'B', 'C'] * 4, 'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2, 'D' : np.random.randn(12), 'E' : np.random.randn(12)}) df We can produce pivot tables from this data very easily: .. ipython:: python pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'])