Examples

In [1]:
import numpy as np
import pandas as pd
In [2]:
df = pd.DataFrame({'Animal': ['Eagle', 'Eagle',
                              'Sparrow','Sparrow'],
                   'Max Speed': [350., 320., 26., 30.]})
df
Out[2]:
Animal Max Speed
0 Eagle 350.0
1 Eagle 320.0
2 Sparrow 26.0
3 Sparrow 30.0
In [3]:
df.groupby(['Animal']).mean()
Out[3]:
Max Speed
Animal
Eagle 335.0
Sparrow 28.0

Hierarchical Indexes
We can groupby different levels of a hierarchical index using the level parameter:

In [4]:
arrays = [['Eagle', 'Eagle', 'Sparrow', 'Sparrow'],
          ['Captive', 'Wild', 'Captive', 'Wild']]
index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
df = pd.DataFrame({'Max Speed': [370., 320., 30., 24.]},
                  index=index)
df
Out[4]:
Max Speed
Animal Type
Eagle Captive 370.0
Wild 320.0
Sparrow Captive 30.0
Wild 24.0
In [5]:
df.groupby(level=0).mean()
Out[5]:
Max Speed
Animal
Eagle 345.0
Sparrow 27.0
In [6]:
df.groupby(level=1).mean()
Out[6]:
Max Speed
Type
Captive 200.0
Wild 172.0