Table Of Contents

Search

Enter search terms or a module, class or function name.

Group By: split-apply-combine

By “group by” we are referring to a process involving one or more of the following steps

  • Splitting the data into groups based on some criteria
  • Applying a function to each group independently
  • Combining the results into a data structure

Of these, the split step is the most straightforward. In fact, in many situations you may wish to split the data set into groups and do something with those groups yourself. In the apply step, we might wish to one of the following:

  • Aggregation: computing a summary statistic (or statistics) about each group. Some examples:

    • Compute group sums or means
    • Compute group sizes / counts
  • Transformation: perform some group-specific computations and return a like-indexed. Some examples:

    • Standardizing data (zscore) within group
    • Filling NAs within groups with a value derived from each group
  • Filtration: discard some groups, according to a group-wise computation that evaluates True or False. Some examples:

    • Discarding data that belongs to groups with only a few members
    • Filtering out data based on the group sum or mean
  • Some combination of the above: GroupBy will examine the results of the apply step and try to return a sensibly combined result if it doesn’t fit into either of the above two categories

Since the set of object instance methods on pandas data structures are generally rich and expressive, we often simply want to invoke, say, a DataFrame function on each group. The name GroupBy should be quite familiar to those who have used a SQL-based tool (or itertools), in which you can write code like:

SELECT Column1, Column2, mean(Column3), sum(Column4)
FROM SomeTable
GROUP BY Column1, Column2

We aim to make operations like this natural and easy to express using pandas. We’ll address each area of GroupBy functionality then provide some non-trivial examples / use cases.

See the cookbook for some advanced strategies

Splitting an object into groups

pandas objects can be split on any of their axes. The abstract definition of grouping is to provide a mapping of labels to group names. To create a GroupBy object (more on what the GroupBy object is later), you do the following:

# default is axis=0
>>> grouped = obj.groupby(key)
>>> grouped = obj.groupby(key, axis=1)
>>> grouped = obj.groupby([key1, key2])

The mapping can be specified many different ways:

  • A Python function, to be called on each of the axis labels
  • A list or NumPy array of the same length as the selected axis
  • A dict or Series, providing a label -> group name mapping
  • For DataFrame objects, a string indicating a column to be used to group. Of course df.groupby('A') is just syntactic sugar for df.groupby(df['A']), but it makes life simpler
  • For DataFrame objects, a string indicating an index level to be used to group.
  • A list of any of the above things

Collectively we refer to the grouping objects as the keys. For example, consider the following DataFrame:

Note

New in version 0.20.

A string passed to groupby may refer to either a column or an index level. If a string matches both a column name and an index level name then a warning is issued and the column takes precedence. This will result in an ambiguity error in a future version.

In [1]: df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
   ...:                           'foo', 'bar', 'foo', 'foo'],
   ...:                    'B' : ['one', 'one', 'two', 'three',
   ...:                           'two', 'two', 'one', 'three'],
   ...:                    'C' : np.random.randn(8),
   ...:                    'D' : np.random.randn(8)})
   ...: 

In [2]: df
Out[2]: 
     A      B         C         D
0  foo    one  0.469112 -0.861849
1  bar    one -0.282863 -2.104569
2  foo    two -1.509059 -0.494929
3  bar  three -1.135632  1.071804
4  foo    two  1.212112  0.721555
5  bar    two -0.173215 -0.706771
6  foo    one  0.119209 -1.039575
7  foo  three -1.044236  0.271860

We could naturally group by either the A or B columns or both:

In [3]: grouped = df.groupby('A')

In [4]: grouped = df.groupby(['A', 'B'])

These will split the DataFrame on its index (rows). We could also split by the columns:

In [5]: def get_letter_type(letter):
   ...:     if letter.lower() in 'aeiou':
   ...:         return 'vowel'
   ...:     else:
   ...:         return 'consonant'
   ...: 

In [6]: grouped = df.groupby(get_letter_type, axis=1)

pandas Index objects support duplicate values. If a non-unique index is used as the group key in a groupby operation, all values for the same index value will be considered to be in one group and thus the output of aggregation functions will only contain unique index values:

In [7]: lst = [1, 2, 3, 1, 2, 3]

In [8]: s = pd.Series([1, 2, 3, 10, 20, 30], lst)

In [9]: grouped = s.groupby(level=0)

In [10]: grouped.first()
Out[10]: 
1    1
2    2
3    3
dtype: int64

In [11]: grouped.last()
Out[11]: 
1    10
2    20
3    30
dtype: int64

In [12]: grouped.sum()
Out[12]: 
1    11
2    22
3    33
dtype: int64

Note that no splitting occurs until it’s needed. Creating the GroupBy object only verifies that you’ve passed a valid mapping.

Note

Many kinds of complicated data manipulations can be expressed in terms of GroupBy operations (though can’t be guaranteed to be the most efficient). You can get quite creative with the label mapping functions.

GroupBy sorting

By default the group keys are sorted during the groupby operation. You may however pass sort=False for potential speedups:

In [13]: df2 = pd.DataFrame({'X' : ['B', 'B', 'A', 'A'], 'Y' : [1, 2, 3, 4]})

In [14]: df2.groupby(['X']).sum()
Out[14]: 
   Y
X   
A  7
B  3

In [15]: df2.groupby(['X'], sort=False).sum()
Out[15]: 
   Y
X   
B  3
A  7

Note that groupby will preserve the order in which observations are sorted within each group. For example, the groups created by groupby() below are in the order they appeared in the original DataFrame:

In [16]: df3 = pd.DataFrame({'X' : ['A', 'B', 'A', 'B'], 'Y' : [1, 4, 3, 2]})

In [17]: df3.groupby(['X']).get_group('A')
Out[17]: 
   X  Y
0  A  1
2  A  3

In [18]: df3.groupby(['X']).get_group('B')
Out[18]: 
   X  Y
1  B  4
3  B  2

GroupBy object attributes

The groups attribute is a dict whose keys are the computed unique groups and corresponding values being the axis labels belonging to each group. In the above example we have:

In [19]: df.groupby('A').groups
Out[19]: 
{'bar': Int64Index([1, 3, 5], dtype='int64'),
 'foo': Int64Index([0, 2, 4, 6, 7], dtype='int64')}

In [20]: df.groupby(get_letter_type, axis=1).groups
Out[20]: 
{'consonant': Index(['B', 'C', 'D'], dtype='object'),
 'vowel': Index(['A'], dtype='object')}

Calling the standard Python len function on the GroupBy object just returns the length of the groups dict, so it is largely just a convenience:

In [21]: grouped = df.groupby(['A', 'B'])

In [22]: grouped.groups
Out[22]: 
{('bar', 'one'): Int64Index([1], dtype='int64'),
 ('bar', 'three'): Int64Index([3], dtype='int64'),
 ('bar', 'two'): Int64Index([5], dtype='int64'),
 ('foo', 'one'): Int64Index([0, 6], dtype='int64'),
 ('foo', 'three'): Int64Index([7], dtype='int64'),
 ('foo', 'two'): Int64Index([2, 4], dtype='int64')}

In [23]: len(grouped)
Out[23]: 6

GroupBy will tab complete column names (and other attributes)

In [24]: df
Out[24]: 
            gender     height      weight
2000-01-01    male  42.849980  157.500553
2000-01-02    male  49.607315  177.340407
2000-01-03    male  56.293531  171.524640
2000-01-04  female  48.421077  144.251986
2000-01-05    male  46.556882  152.526206
2000-01-06  female  68.448851  168.272968
2000-01-07    male  70.757698  136.431469
2000-01-08  female  58.909500  176.499753
2000-01-09  female  76.435631  174.094104
2000-01-10    male  45.306120  177.540920

In [25]: gb = df.groupby('gender')
In [26]: gb.<TAB>
gb.agg        gb.boxplot    gb.cummin     gb.describe   gb.filter     gb.get_group  gb.height     gb.last       gb.median     gb.ngroups    gb.plot       gb.rank       gb.std        gb.transform
gb.aggregate  gb.count      gb.cumprod    gb.dtype      gb.first      gb.groups     gb.hist       gb.max        gb.min        gb.nth        gb.prod       gb.resample   gb.sum        gb.var
gb.apply      gb.cummax     gb.cumsum     gb.fillna     gb.gender     gb.head       gb.indices    gb.mean       gb.name       gb.ohlc       gb.quantile   gb.size       gb.tail       gb.weight

GroupBy with MultiIndex

With hierarchically-indexed data, it’s quite natural to group by one of the levels of the hierarchy.

Let’s create a Series with a two-level MultiIndex.

In [27]: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
   ....:           ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
   ....: 

In [28]: index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])

In [29]: s = pd.Series(np.random.randn(8), index=index)

In [30]: s
Out[30]: 
first  second
bar    one      -0.919854
       two      -0.042379
baz    one       1.247642
       two      -0.009920
foo    one       0.290213
       two       0.495767
qux    one       0.362949
       two       1.548106
dtype: float64

We can then group by one of the levels in s.

In [31]: grouped = s.groupby(level=0)

In [32]: grouped.sum()
Out[32]: 
first
bar   -0.962232
baz    1.237723
foo    0.785980
qux    1.911055
dtype: float64

If the MultiIndex has names specified, these can be passed instead of the level number:

In [33]: s.groupby(level='second').sum()
Out[33]: 
second
one    0.980950
two    1.991575
dtype: float64

The aggregation functions such as sum will take the level parameter directly. Additionally, the resulting index will be named according to the chosen level:

In [34]: s.sum(level='second')
Out[34]: 
second
one    0.980950
two    1.991575
dtype: float64

Grouping with multiple levels is supported.

In [35]: s
Out[35]: 
first  second  third
bar    doo     one     -1.131345
               two     -0.089329
baz    bee     one      0.337863
               two     -0.945867
foo    bop     one     -0.932132
               two      1.956030
qux    bop     one      0.017587
               two     -0.016692
dtype: float64

In [36]: s.groupby(level=['first', 'second']).sum()
Out[36]: 
first  second
bar    doo      -1.220674
baz    bee      -0.608004
foo    bop       1.023898
qux    bop       0.000895
dtype: float64

New in version 0.20.

Index level names may be supplied as keys.

In [37]: s.groupby(['first', 'second']).sum()
Out[37]: 
first  second
bar    doo      -1.220674
baz    bee      -0.608004
foo    bop       1.023898
qux    bop       0.000895
dtype: float64

More on the sum function and aggregation later.

Grouping DataFrame with Index Levels and Columns

A DataFrame may be grouped by a combination of columns and index levels by specifying the column names as strings and the index levels as pd.Grouper objects.

In [38]: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
   ....:           ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
   ....: 

In [39]: index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])

In [40]: df = pd.DataFrame({'A': [1, 1, 1, 1, 2, 2, 3, 3],
   ....:                    'B': np.arange(8)},
   ....:                   index=index)
   ....: 

In [41]: df
Out[41]: 
              A  B
first second      
bar   one     1  0
      two     1  1
baz   one     1  2
      two     1  3
foo   one     2  4
      two     2  5
qux   one     3  6
      two     3  7

The following example groups df by the second index level and the A column.

In [42]: df.groupby([pd.Grouper(level=1), 'A']).sum()
Out[42]: 
          B
second A   
one    1  2
       2  4
       3  6
two    1  4
       2  5
       3  7

Index levels may also be specified by name.

In [43]: df.groupby([pd.Grouper(level='second'), 'A']).sum()
Out[43]: 
          B
second A   
one    1  2
       2  4
       3  6
two    1  4
       2  5
       3  7

New in version 0.20.

Index level names may be specified as keys directly to groupby.

In [44]: df.groupby(['second', 'A']).sum()
Out[44]: 
          B
second A   
one    1  2
       2  4
       3  6
two    1  4
       2  5
       3  7

DataFrame column selection in GroupBy

Once you have created the GroupBy object from a DataFrame, for example, you might want to do something different for each of the columns. Thus, using [] similar to getting a column from a DataFrame, you can do:

In [45]: grouped = df.groupby(['A'])

In [46]: grouped_C = grouped['C']

In [47]: grouped_D = grouped['D']

This is mainly syntactic sugar for the alternative and much more verbose:

In [48]: df['C'].groupby(df['A'])
Out[48]: <pandas.core.groupby.SeriesGroupBy object at 0x7fea52706668>

Additionally this method avoids recomputing the internal grouping information derived from the passed key.

Iterating through groups

With the GroupBy object in hand, iterating through the grouped data is very natural and functions similarly to itertools.groupby:

In [49]: grouped = df.groupby('A')

In [50]: for name, group in grouped:
   ....:        print(name)
   ....:        print(group)
   ....: 
bar
     A      B         C         D
1  bar    one  0.254161  1.511763
3  bar  three  0.215897 -0.990582
5  bar    two -0.077118  1.211526
foo
     A      B         C         D
0  foo    one -0.575247  1.346061
2  foo    two -1.143704  1.627081
4  foo    two  1.193555 -0.441652
6  foo    one -0.408530  0.268520
7  foo  three -0.862495  0.024580

In the case of grouping by multiple keys, the group name will be a tuple:

In [51]: for name, group in df.groupby(['A', 'B']):
   ....:        print(name)
   ....:        print(group)
   ....: 
('bar', 'one')
     A    B         C         D
1  bar  one  0.254161  1.511763
('bar', 'three')
     A      B         C         D
3  bar  three  0.215897 -0.990582
('bar', 'two')
     A    B         C         D
5  bar  two -0.077118  1.211526
('foo', 'one')
     A    B         C         D
0  foo  one -0.575247  1.346061
6  foo  one -0.408530  0.268520
('foo', 'three')
     A      B         C        D
7  foo  three -0.862495  0.02458
('foo', 'two')
     A    B         C         D
2  foo  two -1.143704  1.627081
4  foo  two  1.193555 -0.441652

It’s standard Python-fu but remember you can unpack the tuple in the for loop statement if you wish: for (k1, k2), group in grouped:.

Selecting a group

A single group can be selected using GroupBy.get_group():

In [52]: grouped.get_group('bar')
Out[52]: 
     A      B         C         D
1  bar    one  0.254161  1.511763
3  bar  three  0.215897 -0.990582
5  bar    two -0.077118  1.211526

Or for an object grouped on multiple columns:

In [53]: df.groupby(['A', 'B']).get_group(('bar', 'one'))
Out[53]: 
     A    B         C         D
1  bar  one  0.254161  1.511763

Aggregation

Once the GroupBy object has been created, several methods are available to perform a computation on the grouped data. These operations are similar to the aggregating API, window functions API, and resample API.

An obvious one is aggregation via the aggregate or equivalently agg method:

In [54]: grouped = df.groupby('A')

In [55]: grouped.aggregate(np.sum)
Out[55]: 
            C         D
A                      
bar  0.392940  1.732707
foo -1.796421  2.824590

In [56]: grouped = df.groupby(['A', 'B'])

In [57]: grouped.aggregate(np.sum)
Out[57]: 
                  C         D
A   B                        
bar one    0.254161  1.511763
    three  0.215897 -0.990582
    two   -0.077118  1.211526
foo one   -0.983776  1.614581
    three -0.862495  0.024580
    two    0.049851  1.185429

As you can see, the result of the aggregation will have the group names as the new index along the grouped axis. In the case of multiple keys, the result is a MultiIndex by default, though this can be changed by using the as_index option:

In [58]: grouped = df.groupby(['A', 'B'], as_index=False)

In [59]: grouped.aggregate(np.sum)
Out[59]: 
     A      B         C         D
0  bar    one  0.254161  1.511763
1  bar  three  0.215897 -0.990582
2  bar    two -0.077118  1.211526
3  foo    one -0.983776  1.614581
4  foo  three -0.862495  0.024580
5  foo    two  0.049851  1.185429

In [60]: df.groupby('A', as_index=False).sum()
Out[60]: 
     A         C         D
0  bar  0.392940  1.732707
1  foo -1.796421  2.824590

Note that you could use the reset_index DataFrame function to achieve the same result as the column names are stored in the resulting MultiIndex:

In [61]: df.groupby(['A', 'B']).sum().reset_index()
Out[61]: 
     A      B         C         D
0  bar    one  0.254161  1.511763
1  bar  three  0.215897 -0.990582
2  bar    two -0.077118  1.211526
3  foo    one -0.983776  1.614581
4  foo  three -0.862495  0.024580
5  foo    two  0.049851  1.185429

Another simple aggregation example is to compute the size of each group. This is included in GroupBy as the size method. It returns a Series whose index are the group names and whose values are the sizes of each group.

In [62]: grouped.size()
Out[62]: 
A    B    
bar  one      1
     three    1
     two      1
foo  one      2
     three    1
     two      2
dtype: int64
In [63]: grouped.describe()
Out[63]: 
      C                                                                        \
  count      mean       std       min       25%       50%       75%       max   
0   1.0  0.254161       NaN  0.254161  0.254161  0.254161  0.254161  0.254161   
1   1.0  0.215897       NaN  0.215897  0.215897  0.215897  0.215897  0.215897   
2   1.0 -0.077118       NaN -0.077118 -0.077118 -0.077118 -0.077118 -0.077118   
3   2.0 -0.491888  0.117887 -0.575247 -0.533567 -0.491888 -0.450209 -0.408530   
4   1.0 -0.862495       NaN -0.862495 -0.862495 -0.862495 -0.862495 -0.862495   
5   2.0  0.024925  1.652692 -1.143704 -0.559389  0.024925  0.609240  1.193555   

      D                                                                        
  count      mean       std       min       25%       50%       75%       max  
0   1.0  1.511763       NaN  1.511763  1.511763  1.511763  1.511763  1.511763  
1   1.0 -0.990582       NaN -0.990582 -0.990582 -0.990582 -0.990582 -0.990582  
2   1.0  1.211526       NaN  1.211526  1.211526  1.211526  1.211526  1.211526  
3   2.0  0.807291  0.761937  0.268520  0.537905  0.807291  1.076676  1.346061  
4   1.0  0.024580       NaN  0.024580  0.024580  0.024580  0.024580  0.024580  
5   2.0  0.592714  1.462816 -0.441652  0.075531  0.592714  1.109898  1.627081  

Note

Aggregation functions will not return the groups that you are aggregating over if they are named columns, when as_index=True, the default. The grouped columns will be the indices of the returned object.

Passing as_index=False will return the groups that you are aggregating over, if they are named columns.

Aggregating functions are ones that reduce the dimension of the returned objects, for example: mean, sum, size, count, std, var, sem, describe, first, last, nth, min, max. This is what happens when you do for example DataFrame.sum() and get back a Series.

nth can act as a reducer or a filter, see here

Applying multiple functions at once

With grouped Series you can also pass a list or dict of functions to do aggregation with, outputting a DataFrame:

In [64]: grouped = df.groupby('A')

In [65]: grouped['C'].agg([np.sum, np.mean, np.std])
Out[65]: 
          sum      mean       std
A                                
bar  0.392940  0.130980  0.181231
foo -1.796421 -0.359284  0.912265

On a grouped DataFrame, you can pass a list of functions to apply to each column, which produces an aggregated result with a hierarchical index:

In [66]: grouped.agg([np.sum, np.mean, np.std])
Out[66]: 
            C                             D                    
          sum      mean       std       sum      mean       std
A                                                              
bar  0.392940  0.130980  0.181231  1.732707  0.577569  1.366330
foo -1.796421 -0.359284  0.912265  2.824590  0.564918  0.884785

The resulting aggregations are named for the functions themselves. If you need to rename, then you can add in a chained operation for a Series like this:

In [67]: (grouped['C'].agg([np.sum, np.mean, np.std])
   ....:              .rename(columns={'sum': 'foo',
   ....:                               'mean': 'bar',
   ....:                               'std': 'baz'})
   ....: )
   ....: 
Out[67]: 
          foo       bar       baz
A                                
bar  0.392940  0.130980  0.181231
foo -1.796421 -0.359284  0.912265

For a grouped DataFrame, you can rename in a similar manner:

In [68]: (grouped.agg([np.sum, np.mean, np.std])
   ....:         .rename(columns={'sum': 'foo',
   ....:                          'mean': 'bar',
   ....:                          'std': 'baz'})
   ....:  )
   ....: 
Out[68]: 
            C                             D                    
          foo       bar       baz       foo       bar       baz
A                                                              
bar  0.392940  0.130980  0.181231  1.732707  0.577569  1.366330
foo -1.796421 -0.359284  0.912265  2.824590  0.564918  0.884785

Applying different functions to DataFrame columns

By passing a dict to aggregate you can apply a different aggregation to the columns of a DataFrame:

In [69]: grouped.agg({'C' : np.sum,
   ....:              'D' : lambda x: np.std(x, ddof=1)})
   ....: 
Out[69]: 
            C         D
A                      
bar  0.392940  1.366330
foo -1.796421  0.884785

The function names can also be strings. In order for a string to be valid it must be either implemented on GroupBy or available via dispatching:

In [70]: grouped.agg({'C' : 'sum', 'D' : 'std'})
Out[70]: 
            C         D
A                      
bar  0.392940  1.366330
foo -1.796421  0.884785

Note

If you pass a dict to aggregate, the ordering of the output columns is non-deterministic. If you want to be sure the output columns will be in a specific order, you can use an OrderedDict. Compare the output of the following two commands:

In [71]: grouped.agg({'D': 'std', 'C': 'mean'})
Out[71]: 
            D         C
A                      
bar  1.366330  0.130980
foo  0.884785 -0.359284

In [72]: grouped.agg(OrderedDict([('D', 'std'), ('C', 'mean')]))
Out[72]: 
            D         C
A                      
bar  1.366330  0.130980
foo  0.884785 -0.359284

Cython-optimized aggregation functions

Some common aggregations, currently only sum, mean, std, and sem, have optimized Cython implementations:

In [73]: df.groupby('A').sum()
Out[73]: 
            C         D
A                      
bar  0.392940  1.732707
foo -1.796421  2.824590

In [74]: df.groupby(['A', 'B']).mean()
Out[74]: 
                  C         D
A   B                        
bar one    0.254161  1.511763
    three  0.215897 -0.990582
    two   -0.077118  1.211526
foo one   -0.491888  0.807291
    three -0.862495  0.024580
    two    0.024925  0.592714

Of course sum and mean are implemented on pandas objects, so the above code would work even without the special versions via dispatching (see below).

Transformation

The transform method returns an object that is indexed the same (same size) as the one being grouped. The transform function must:

  • Return a result that is either the same size as the group chunk or broadcastable to the size of the group chunk (e.g., a scalar, grouped.transform(lambda x: x.iloc[-1])).
  • Operate column-by-column on the group chunk. The transform is applied to the first group chunk using chunk.apply.
  • Not perform in-place operations on the group chunk. Group chunks should be treated as immutable, and changes to a group chunk may produce unexpected results. For example, when using fillna, inplace must be False (grouped.transform(lambda x: x.fillna(inplace=False))).
  • (Optionally) operates on the entire group chunk. If this is supported, a fast path is used starting from the second chunk.

For example, suppose we wished to standardize the data within each group:

In [75]: index = pd.date_range('10/1/1999', periods=1100)

In [76]: ts = pd.Series(np.random.normal(0.5, 2, 1100), index)

In [77]: ts = ts.rolling(window=100,min_periods=100).mean().dropna()

In [78]: ts.head()
Out[78]: 
2000-01-08    0.779333
2000-01-09    0.778852
2000-01-10    0.786476
2000-01-11    0.782797
2000-01-12    0.798110
Freq: D, dtype: float64

In [79]: ts.tail()
Out[79]: 
2002-09-30    0.660294
2002-10-01    0.631095
2002-10-02    0.673601
2002-10-03    0.709213
2002-10-04    0.719369
Freq: D, dtype: float64

In [80]: key = lambda x: x.year

In [81]: zscore = lambda x: (x - x.mean()) / x.std()

In [82]: transformed = ts.groupby(key).transform(zscore)

We would expect the result to now have mean 0 and standard deviation 1 within each group, which we can easily check:

# Original Data
In [83]: grouped = ts.groupby(key)

In [84]: grouped.mean()
Out[84]: 
2000    0.442441
2001    0.526246
2002    0.459365
dtype: float64

In [85]: grouped.std()
Out[85]: 
2000    0.131752
2001    0.210945
2002    0.128753
dtype: float64

# Transformed Data
In [86]: grouped_trans = transformed.groupby(key)

In [87]: grouped_trans.mean()
Out[87]: 
2000    1.168208e-15
2001    1.454544e-15
2002    1.726657e-15
dtype: float64

In [88]: grouped_trans.std()
Out[88]: 
2000    1.0
2001    1.0
2002    1.0
dtype: float64

We can also visually compare the original and transformed data sets.

In [89]: compare = pd.DataFrame({'Original': ts, 'Transformed': transformed})

In [90]: compare.plot()
Out[90]: <matplotlib.axes._subplots.AxesSubplot at 0x7fea4f087e48>
_images/groupby_transform_plot.png

Transformation functions that have lower dimension outputs are broadcast to match the shape of the input array.

In [91]: data_range = lambda x: x.max() - x.min()

In [92]: ts.groupby(key).transform(data_range)
Out[92]: 
2000-01-08    0.623893
2000-01-09    0.623893
2000-01-10    0.623893
2000-01-11    0.623893
2000-01-12    0.623893
2000-01-13    0.623893
2000-01-14    0.623893
                ...   
2002-09-28    0.558275
2002-09-29    0.558275
2002-09-30    0.558275
2002-10-01    0.558275
2002-10-02    0.558275
2002-10-03    0.558275
2002-10-04    0.558275
Freq: D, Length: 1001, dtype: float64

Alternatively the built-in methods can be could be used to produce the same outputs

In [93]: ts.groupby(key).transform('max') - ts.groupby(key).transform('min')
Out[93]: 
2000-01-08    0.623893
2000-01-09    0.623893
2000-01-10    0.623893
2000-01-11    0.623893
2000-01-12    0.623893
2000-01-13    0.623893
2000-01-14    0.623893
                ...   
2002-09-28    0.558275
2002-09-29    0.558275
2002-09-30    0.558275
2002-10-01    0.558275
2002-10-02    0.558275
2002-10-03    0.558275
2002-10-04    0.558275
Freq: D, Length: 1001, dtype: float64

Another common data transform is to replace missing data with the group mean.

In [94]: data_df
Out[94]: 
            A         B         C
0    1.539708 -1.166480  0.533026
1    1.302092 -0.505754       NaN
2   -0.371983  1.104803 -0.651520
3   -1.309622  1.118697 -1.161657
4   -1.924296  0.396437  0.812436
5    0.815643  0.367816 -0.469478
6   -0.030651  1.376106 -0.645129
..        ...       ...       ...
993  0.012359  0.554602 -1.976159
994  0.042312 -1.628835  1.013822
995 -0.093110  0.683847 -0.774753
996 -0.185043  1.438572       NaN
997 -0.394469 -0.642343  0.011374
998 -1.174126  1.857148       NaN
999  0.234564  0.517098  0.393534

[1000 rows x 3 columns]

In [95]: countries = np.array(['US', 'UK', 'GR', 'JP'])

In [96]: key = countries[np.random.randint(0, 4, 1000)]

In [97]: grouped = data_df.groupby(key)

# Non-NA count in each group
In [98]: grouped.count()
Out[98]: 
      A    B    C
GR  209  217  189
JP  240  255  217
UK  216  231  193
US  239  250  217

In [99]: f = lambda x: x.fillna(x.mean())

In [100]: transformed = grouped.transform(f)

We can verify that the group means have not changed in the transformed data and that the transformed data contains no NAs.

In [101]: grouped_trans = transformed.groupby(key)

In [102]: grouped.mean() # original group means
Out[102]: 
           A         B         C
GR -0.098371 -0.015420  0.068053
JP  0.069025  0.023100 -0.077324
UK  0.034069 -0.052580 -0.116525
US  0.058664 -0.020399  0.028603

In [103]: grouped_trans.mean() # transformation did not change group means
Out[103]: 
           A         B         C
GR -0.098371 -0.015420  0.068053
JP  0.069025  0.023100 -0.077324
UK  0.034069 -0.052580 -0.116525
US  0.058664 -0.020399  0.028603

In [104]: grouped.count() # original has some missing data points
Out[104]: 
      A    B    C
GR  209  217  189
JP  240  255  217
UK  216  231  193
US  239  250  217

In [105]: grouped_trans.count() # counts after transformation
Out[105]: 
      A    B    C
GR  228  228  228
JP  267  267  267
UK  247  247  247
US  258  258  258

In [106]: grouped_trans.size() # Verify non-NA count equals group size
Out[106]: 
GR    228
JP    267
UK    247
US    258
dtype: int64

Note

Some functions when applied to a groupby object will automatically transform the input, returning an object of the same shape as the original. Passing as_index=False will not affect these transformation methods.

For example: fillna, ffill, bfill, shift.

In [107]: grouped.ffill()
Out[107]: 
            A         B         C
0    1.539708 -1.166480  0.533026
1    1.302092 -0.505754  0.533026
2   -0.371983  1.104803 -0.651520
3   -1.309622  1.118697 -1.161657
4   -1.924296  0.396437  0.812436
5    0.815643  0.367816 -0.469478
6   -0.030651  1.376106 -0.645129
..        ...       ...       ...
993  0.012359  0.554602 -1.976159
994  0.042312 -1.628835  1.013822
995 -0.093110  0.683847 -0.774753
996 -0.185043  1.438572 -0.774753
997 -0.394469 -0.642343  0.011374
998 -1.174126  1.857148 -0.774753
999  0.234564  0.517098  0.393534

[1000 rows x 3 columns]

New syntax to window and resample operations

New in version 0.18.1.

Working with the resample, expanding or rolling operations on the groupby level used to require the application of helper functions. However, now it is possible to use resample(), expanding() and rolling() as methods on groupbys.

The example below will apply the rolling() method on the samples of the column B based on the groups of column A.

In [108]: df_re = pd.DataFrame({'A': [1] * 10 + [5] * 10,
   .....:                       'B': np.arange(20)})
   .....: 

In [109]: df_re
Out[109]: 
    A   B
0   1   0
1   1   1
2   1   2
3   1   3
4   1   4
5   1   5
6   1   6
.. ..  ..
13  5  13
14  5  14
15  5  15
16  5  16
17  5  17
18  5  18
19  5  19

[20 rows x 2 columns]

In [110]: df_re.groupby('A').rolling(4).B.mean()
Out[110]: 
A    
1  0      NaN
   1      NaN
   2      NaN
   3      1.5
   4      2.5
   5      3.5
   6      4.5
         ... 
5  13    11.5
   14    12.5
   15    13.5
   16    14.5
   17    15.5
   18    16.5
   19    17.5
Name: B, Length: 20, dtype: float64

The expanding() method will accumulate a given operation (sum() in the example) for all the members of each particular group.

In [111]: df_re.groupby('A').expanding().sum()
Out[111]: 
         A      B
A                
1 0    1.0    0.0
  1    2.0    1.0
  2    3.0    3.0
  3    4.0    6.0
  4    5.0   10.0
  5    6.0   15.0
  6    7.0   21.0
...    ...    ...
5 13  20.0   46.0
  14  25.0   60.0
  15  30.0   75.0
  16  35.0   91.0
  17  40.0  108.0
  18  45.0  126.0
  19  50.0  145.0

[20 rows x 2 columns]

Suppose you want to use the resample() method to get a daily frequency in each group of your dataframe and wish to complete the missing values with the ffill() method.

In [112]: df_re = pd.DataFrame({'date': pd.date_range(start='2016-01-01',
   .....:                               periods=4,
   .....:                       freq='W'),
   .....:                      'group': [1, 1, 2, 2],
   .....:                      'val': [5, 6, 7, 8]}).set_index('date')
   .....: 

In [113]: df_re
Out[113]: 
            group  val
date                  
2016-01-03      1    5
2016-01-10      1    6
2016-01-17      2    7
2016-01-24      2    8

In [114]: df_re.groupby('group').resample('1D').ffill()
Out[114]: 
                  group  val
group date                  
1     2016-01-03      1    5
      2016-01-04      1    5
      2016-01-05      1    5
      2016-01-06      1    5
      2016-01-07      1    5
      2016-01-08      1    5
      2016-01-09      1    5
...                 ...  ...
2     2016-01-18      2    7
      2016-01-19      2    7
      2016-01-20      2    7
      2016-01-21      2    7
      2016-01-22      2    7
      2016-01-23      2    7
      2016-01-24      2    8

[16 rows x 2 columns]

Filtration

The filter method returns a subset of the original object. Suppose we want to take only elements that belong to groups with a group sum greater than 2.

In [115]: sf = pd.Series([1, 1, 2, 3, 3, 3])

In [116]: sf.groupby(sf).filter(lambda x: x.sum() > 2)
Out[116]: 
3    3
4    3
5    3
dtype: int64

The argument of filter must be a function that, applied to the group as a whole, returns True or False.

Another useful operation is filtering out elements that belong to groups with only a couple members.

In [117]: dff = pd.DataFrame({'A': np.arange(8), 'B': list('aabbbbcc')})

In [118]: dff.groupby('B').filter(lambda x: len(x) > 2)
Out[118]: 
   A  B
2  2  b
3  3  b
4  4  b
5  5  b

Alternatively, instead of dropping the offending groups, we can return a like-indexed objects where the groups that do not pass the filter are filled with NaNs.

In [119]: dff.groupby('B').filter(lambda x: len(x) > 2, dropna=False)
Out[119]: 
     A    B
0  NaN  NaN
1  NaN  NaN
2  2.0    b
3  3.0    b
4  4.0    b
5  5.0    b
6  NaN  NaN
7  NaN  NaN

For DataFrames with multiple columns, filters should explicitly specify a column as the filter criterion.

In [120]: dff['C'] = np.arange(8)

In [121]: dff.groupby('B').filter(lambda x: len(x['C']) > 2)
Out[121]: 
   A  B  C
2  2  b  2
3  3  b  3
4  4  b  4
5  5  b  5

Note

Some functions when applied to a groupby object will act as a filter on the input, returning a reduced shape of the original (and potentially eliminating groups), but with the index unchanged. Passing as_index=False will not affect these transformation methods.

For example: head, tail.

In [122]: dff.groupby('B').head(2)
Out[122]: 
   A  B  C
0  0  a  0
1  1  a  1
2  2  b  2
3  3  b  3
6  6  c  6
7  7  c  7

Dispatching to instance methods

When doing an aggregation or transformation, you might just want to call an instance method on each data group. This is pretty easy to do by passing lambda functions:

In [123]: grouped = df.groupby('A')

In [124]: grouped.agg(lambda x: x.std())
Out[124]: 
            C         D
A                      
bar  0.181231  1.366330
foo  0.912265  0.884785

But, it’s rather verbose and can be untidy if you need to pass additional arguments. Using a bit of metaprogramming cleverness, GroupBy now has the ability to “dispatch” method calls to the groups:

In [125]: grouped.std()
Out[125]: 
            C         D
A                      
bar  0.181231  1.366330
foo  0.912265  0.884785

What is actually happening here is that a function wrapper is being generated. When invoked, it takes any passed arguments and invokes the function with any arguments on each group (in the above example, the std function). The results are then combined together much in the style of agg and transform (it actually uses apply to infer the gluing, documented next). This enables some operations to be carried out rather succinctly:

In [126]: tsdf = pd.DataFrame(np.random.randn(1000, 3),
   .....:                     index=pd.date_range('1/1/2000', periods=1000),
   .....:                     columns=['A', 'B', 'C'])
   .....: 

In [127]: tsdf.iloc[::2] = np.nan

In [128]: grouped = tsdf.groupby(lambda x: x.year)

In [129]: grouped.fillna(method='pad')
Out[129]: 
                   A         B         C
2000-01-01       NaN       NaN       NaN
2000-01-02 -0.353501 -0.080957 -0.876864
2000-01-03 -0.353501 -0.080957 -0.876864
2000-01-04  0.050976  0.044273 -0.559849
2000-01-05  0.050976  0.044273 -0.559849
2000-01-06  0.030091  0.186460 -0.680149
2000-01-07  0.030091  0.186460 -0.680149
...              ...       ...       ...
2002-09-20  2.310215  0.157482 -0.064476
2002-09-21  2.310215  0.157482 -0.064476
2002-09-22  0.005011  0.053897 -1.026922
2002-09-23  0.005011  0.053897 -1.026922
2002-09-24 -0.456542 -1.849051  1.559856
2002-09-25 -0.456542 -1.849051  1.559856
2002-09-26  1.123162  0.354660  1.128135

[1000 rows x 3 columns]

In this example, we chopped the collection of time series into yearly chunks then independently called fillna on the groups.

The nlargest and nsmallest methods work on Series style groupbys:

In [130]: s = pd.Series([9, 8, 7, 5, 19, 1, 4.2, 3.3])

In [131]: g = pd.Series(list('abababab'))

In [132]: gb = s.groupby(g)

In [133]: gb.nlargest(3)
Out[133]: 
a  4    19.0
   0     9.0
   2     7.0
b  1     8.0
   3     5.0
   7     3.3
dtype: float64

In [134]: gb.nsmallest(3)
Out[134]: 
a  6    4.2
   2    7.0
   0    9.0
b  5    1.0
   7    3.3
   3    5.0
dtype: float64

Flexible apply

Some operations on the grouped data might not fit into either the aggregate or transform categories. Or, you may simply want GroupBy to infer how to combine the results. For these, use the apply function, which can be substituted for both aggregate and transform in many standard use cases. However, apply can handle some exceptional use cases, for example:

In [135]: df
Out[135]: 
     A      B         C         D
0  foo    one -0.575247  1.346061
1  bar    one  0.254161  1.511763
2  foo    two -1.143704  1.627081
3  bar  three  0.215897 -0.990582
4  foo    two  1.193555 -0.441652
5  bar    two -0.077118  1.211526
6  foo    one -0.408530  0.268520
7  foo  three -0.862495  0.024580

In [136]: grouped = df.groupby('A')

# could also just call .describe()
In [137]: grouped['C'].apply(lambda x: x.describe())
Out[137]: 
A         
bar  count    3.000000
     mean     0.130980
     std      0.181231
     min     -0.077118
     25%      0.069390
     50%      0.215897
     75%      0.235029
                ...   
foo  mean    -0.359284
     std      0.912265
     min     -1.143704
     25%     -0.862495
     50%     -0.575247
     75%     -0.408530
     max      1.193555
Name: C, Length: 16, dtype: float64

The dimension of the returned result can also change:

In [138]: grouped = df.groupby('A')['C']

In [139]: def f(group):
   .....:     return pd.DataFrame({'original' : group,
   .....:                          'demeaned' : group - group.mean()})
   .....: 

In [140]: grouped.apply(f)
Out[140]: 
   demeaned  original
0 -0.215962 -0.575247
1  0.123181  0.254161
2 -0.784420 -1.143704
3  0.084917  0.215897
4  1.552839  1.193555
5 -0.208098 -0.077118
6 -0.049245 -0.408530
7 -0.503211 -0.862495

apply on a Series can operate on a returned value from the applied function, that is itself a series, and possibly upcast the result to a DataFrame

In [141]: def f(x):
   .....:   return pd.Series([ x, x**2 ], index = ['x', 'x^2'])
   .....: 

In [142]: s
Out[142]: 
0     9.0
1     8.0
2     7.0
3     5.0
4    19.0
5     1.0
6     4.2
7     3.3
dtype: float64

In [143]: s.apply(f)
Out[143]: 
      x     x^2
0   9.0   81.00
1   8.0   64.00
2   7.0   49.00
3   5.0   25.00
4  19.0  361.00
5   1.0    1.00
6   4.2   17.64
7   3.3   10.89

Note

apply can act as a reducer, transformer, or filter function, depending on exactly what is passed to it. So depending on the path taken, and exactly what you are grouping. Thus the grouped columns(s) may be included in the output as well as set the indices.

Warning

In the current implementation apply calls func twice on the first group to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if func has side-effects, as they will take effect twice for the first group.

In [144]: d = pd.DataFrame({"a":["x", "y"], "b":[1,2]})

In [145]: def identity(df):
   .....:     print(df)
   .....:     return df
   .....: 

In [146]: d.groupby("a").apply(identity)
   a  b
0  x  1
   a  b
0  x  1
   a  b
1  y  2
Out[146]: 
   a  b
0  x  1
1  y  2

Other useful features

Automatic exclusion of “nuisance” columns

Again consider the example DataFrame we’ve been looking at:

In [147]: df
Out[147]: 
     A      B         C         D
0  foo    one -0.575247  1.346061
1  bar    one  0.254161  1.511763
2  foo    two -1.143704  1.627081
3  bar  three  0.215897 -0.990582
4  foo    two  1.193555 -0.441652
5  bar    two -0.077118  1.211526
6  foo    one -0.408530  0.268520
7  foo  three -0.862495  0.024580

Suppose we wish to compute the standard deviation grouped by the A column. There is a slight problem, namely that we don’t care about the data in column B. We refer to this as a “nuisance” column. If the passed aggregation function can’t be applied to some columns, the troublesome columns will be (silently) dropped. Thus, this does not pose any problems:

In [148]: df.groupby('A').std()
Out[148]: 
            C         D
A                      
bar  0.181231  1.366330
foo  0.912265  0.884785

NA and NaT group handling

If there are any NaN or NaT values in the grouping key, these will be automatically excluded. So there will never be an “NA group” or “NaT group”. This was not the case in older versions of pandas, but users were generally discarding the NA group anyway (and supporting it was an implementation headache).

Grouping with ordered factors

Categorical variables represented as instance of pandas’s Categorical class can be used as group keys. If so, the order of the levels will be preserved:

In [149]: data = pd.Series(np.random.randn(100))

In [150]: factor = pd.qcut(data, [0, .25, .5, .75, 1.])

In [151]: data.groupby(factor).mean()
Out[151]: 
(-2.618, -0.684]    -1.331461
(-0.684, -0.0232]   -0.272816
(-0.0232, 0.541]     0.263607
(0.541, 2.369]       1.166038
dtype: float64

Grouping with a Grouper specification

You may need to specify a bit more data to properly group. You can use the pd.Grouper to provide this local control.

In [152]: import datetime

In [153]: df = pd.DataFrame({
   .....:          'Branch' : 'A A A A A A A B'.split(),
   .....:          'Buyer': 'Carl Mark Carl Carl Joe Joe Joe Carl'.split(),
   .....:          'Quantity': [1,3,5,1,8,1,9,3],
   .....:          'Date' : [
   .....:              datetime.datetime(2013,1,1,13,0),
   .....:              datetime.datetime(2013,1,1,13,5),
   .....:              datetime.datetime(2013,10,1,20,0),
   .....:              datetime.datetime(2013,10,2,10,0),
   .....:              datetime.datetime(2013,10,1,20,0),
   .....:              datetime.datetime(2013,10,2,10,0),
   .....:              datetime.datetime(2013,12,2,12,0),
   .....:              datetime.datetime(2013,12,2,14,0),
   .....:              ]
   .....:          })
   .....: 

In [154]: df
Out[154]: 
  Branch Buyer                Date  Quantity
0      A  Carl 2013-01-01 13:00:00         1
1      A  Mark 2013-01-01 13:05:00         3
2      A  Carl 2013-10-01 20:00:00         5
3      A  Carl 2013-10-02 10:00:00         1
4      A   Joe 2013-10-01 20:00:00         8
5      A   Joe 2013-10-02 10:00:00         1
6      A   Joe 2013-12-02 12:00:00         9
7      B  Carl 2013-12-02 14:00:00         3

Groupby a specific column with the desired frequency. This is like resampling.

In [155]: df.groupby([pd.Grouper(freq='1M',key='Date'),'Buyer']).sum()
Out[155]: 
                  Quantity
Date       Buyer          
2013-01-31 Carl          1
           Mark          3
2013-10-31 Carl          6
           Joe           9
2013-12-31 Carl          3
           Joe           9

You have an ambiguous specification in that you have a named index and a column that could be potential groupers.

In [156]: df = df.set_index('Date')

In [157]: df['Date'] = df.index + pd.offsets.MonthEnd(2)

In [158]: df.groupby([pd.Grouper(freq='6M',key='Date'),'Buyer']).sum()
Out[158]: 
                  Quantity
Date       Buyer          
2013-02-28 Carl          1
           Mark          3
2014-02-28 Carl          9
           Joe          18

In [159]: df.groupby([pd.Grouper(freq='6M',level='Date'),'Buyer']).sum()
Out[159]: 
                  Quantity
Date       Buyer          
2013-01-31 Carl          1
           Mark          3
2014-01-31 Carl          9
           Joe          18

Taking the first rows of each group

Just like for a DataFrame or Series you can call head and tail on a groupby:

In [160]: df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])

In [161]: df
Out[161]: 
   A  B
0  1  2
1  1  4
2  5  6

In [162]: g = df.groupby('A')

In [163]: g.head(1)
Out[163]: 
   A  B
0  1  2
2  5  6

In [164]: g.tail(1)
Out[164]: 
   A  B
1  1  4
2  5  6

This shows the first or last n rows from each group.

Taking the nth row of each group

To select from a DataFrame or Series the nth item, use the nth method. This is a reduction method, and will return a single row (or no row) per group if you pass an int for n:

In [165]: df = pd.DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])

In [166]: g = df.groupby('A')

In [167]: g.nth(0)
Out[167]: 
     B
A     
1  NaN
5  6.0

In [168]: g.nth(-1)
Out[168]: 
     B
A     
1  4.0
5  6.0

In [169]: g.nth(1)
Out[169]: 
     B
A     
1  4.0

If you want to select the nth not-null item, use the dropna kwarg. For a DataFrame this should be either 'any' or 'all' just like you would pass to dropna:

# nth(0) is the same as g.first()
In [170]: g.nth(0, dropna='any')
Out[170]: 
     B
A     
1  4.0
5  6.0

In [171]: g.first()
Out[171]: 
     B
A     
1  4.0
5  6.0

# nth(-1) is the same as g.last()
In [172]: g.nth(-1, dropna='any')  # NaNs denote group exhausted when using dropna
Out[172]: 
     B
A     
1  4.0
5  6.0

In [173]: g.last()
Out[173]: 
     B
A     
1  4.0
5  6.0

In [174]: g.B.nth(0, dropna='all')
Out[174]: 
A
1    4.0
5    6.0
Name: B, dtype: float64

As with other methods, passing as_index=False, will achieve a filtration, which returns the grouped row.

In [175]: df = pd.DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])

In [176]: g = df.groupby('A',as_index=False)

In [177]: g.nth(0)
Out[177]: 
   A    B
0  1  NaN
2  5  6.0

In [178]: g.nth(-1)
Out[178]: 
   A    B
1  1  4.0
2  5  6.0

You can also select multiple rows from each group by specifying multiple nth values as a list of ints.

In [179]: business_dates = pd.date_range(start='4/1/2014', end='6/30/2014', freq='B')

In [180]: df = pd.DataFrame(1, index=business_dates, columns=['a', 'b'])

# get the first, 4th, and last date index for each month
In [181]: df.groupby((df.index.year, df.index.month)).nth([0, 3, -1])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-181-4ee0b7a7fa4f> in <module>()
----> 1 df.groupby((df.index.year, df.index.month)).nth([0, 3, -1])

~/build/pandas-dev/pandas/pandas/core/groupby.py in nth(self, n, dropna)
   1384 
   1385         if not dropna:
-> 1386             mask = np.in1d(self._cumcount_array(), nth_values) | \
   1387                 np.in1d(self._cumcount_array(ascending=False) + 1, -nth_values)
   1388 

~/build/pandas-dev/pandas/pandas/core/groupby.py in _cumcount_array(self, ascending)
    748         (though the default is sort=True) for groupby in general
    749         """
--> 750         ids, _, ngroups = self.grouper.group_info
    751         sorter = get_group_index_sorter(ids, ngroups)
    752         ids, count = ids[sorter], len(ids)

~/build/pandas-dev/pandas/pandas/_libs/properties.pyx in pandas._libs.properties.cache_readonly.__get__()

~/build/pandas-dev/pandas/pandas/core/groupby.py in group_info(self)
   1951     @cache_readonly
   1952     def group_info(self):
-> 1953         comp_ids, obs_group_ids = self._get_compressed_labels()
   1954 
   1955         ngroups = len(obs_group_ids)

~/build/pandas-dev/pandas/pandas/core/groupby.py in _get_compressed_labels(self)
   1967 
   1968     def _get_compressed_labels(self):
-> 1969         all_labels = [ping.labels for ping in self.groupings]
   1970         if len(all_labels) > 1:
   1971             group_index = get_group_index(all_labels, self.shape,

~/build/pandas-dev/pandas/pandas/core/groupby.py in <listcomp>(.0)
   1967 
   1968     def _get_compressed_labels(self):
-> 1969         all_labels = [ping.labels for ping in self.groupings]
   1970         if len(all_labels) > 1:
   1971             group_index = get_group_index(all_labels, self.shape,

~/build/pandas-dev/pandas/pandas/core/groupby.py in labels(self)
   2658     def labels(self):
   2659         if self._labels is None:
-> 2660             self._make_labels()
   2661         return self._labels
   2662 

~/build/pandas-dev/pandas/pandas/core/groupby.py in _make_labels(self)
   2675             else:
   2676                 labels, uniques = algorithms.factorize(
-> 2677                     self.grouper, sort=self.sort)
   2678                 uniques = Index(uniques, name=self.name)
   2679             self._labels = labels

~/build/pandas-dev/pandas/pandas/core/algorithms.py in factorize(values, sort, order, na_sentinel, size_hint)
    469     uniques = vec_klass()
    470     check_nulls = not is_integer_dtype(original)
--> 471     labels = table.get_labels(values, uniques, 0, na_sentinel, check_nulls)
    472 
    473     labels = _ensure_platform_int(labels)

~/build/pandas-dev/pandas/pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_labels()

~/build/pandas-dev/pandas/pandas/core/indexes/base.py in __hash__(self)
   1722 
   1723     def __hash__(self):
-> 1724         raise TypeError("unhashable type: %r" % type(self).__name__)
   1725 
   1726     def __setitem__(self, key, value):

TypeError: unhashable type: 'Int64Index'

Enumerate group items

To see the order in which each row appears within its group, use the cumcount method:

In [182]: dfg = pd.DataFrame(list('aaabba'), columns=['A'])

In [183]: dfg
Out[183]: 
   A
0  a
1  a
2  a
3  b
4  b
5  a

In [184]: dfg.groupby('A').cumcount()
Out[184]: 
0    0
1    1
2    2
3    0
4    1
5    3
dtype: int64

In [185]: dfg.groupby('A').cumcount(ascending=False)
Out[185]: 
0    3
1    2
2    1
3    1
4    0
5    0
dtype: int64

Enumerate groups

New in version 0.20.2.

To see the ordering of the groups (as opposed to the order of rows within a group given by cumcount) you can use the ngroup method.

Note that the numbers given to the groups match the order in which the groups would be seen when iterating over the groupby object, not the order they are first observed.

In [186]: dfg = pd.DataFrame(list('aaabba'), columns=['A'])

In [187]: dfg
Out[187]: 
   A
0  a
1  a
2  a
3  b
4  b
5  a

In [188]: dfg.groupby('A').ngroup()
Out[188]: 
0    0
1    0
2    0
3    1
4    1
5    0
dtype: int64

In [189]: dfg.groupby('A').ngroup(ascending=False)
Out[189]: 
0    1
1    1
2    1
3    0
4    0
5    1
dtype: int64

Plotting

Groupby also works with some plotting methods. For example, suppose we suspect that some features in a DataFrame may differ by group, in this case, the values in column 1 where the group is “B” are 3 higher on average.

In [190]: np.random.seed(1234)

In [191]: df = pd.DataFrame(np.random.randn(50, 2))

In [192]: df['g'] = np.random.choice(['A', 'B'], size=50)

In [193]: df.loc[df['g'] == 'B', 1] += 3

We can easily visualize this with a boxplot:

In [194]: df.groupby('g').boxplot()
Out[194]: 
A         AxesSubplot(0.1,0.15;0.363636x0.75)
B    AxesSubplot(0.536364,0.15;0.363636x0.75)
dtype: object
_images/groupby_boxplot.png

The result of calling boxplot is a dictionary whose keys are the values of our grouping column g (“A” and “B”). The values of the resulting dictionary can be controlled by the return_type keyword of boxplot. See the visualization documentation for more.

Warning

For historical reasons, df.groupby("g").boxplot() is not equivalent to df.boxplot(by="g"). See here for an explanation.

Piping function calls

New in version 0.21.0.

Similar to the functionality provided by DataFrame and Series, functions that take GroupBy objects can be chained together using a pipe method to allow for a cleaner, more readable syntax. To read about .pipe in general terms, see here.

Combining .groupby and .pipe is often useful when you need to reuse GroupB objects.

For an example, imagine having a DataFrame with columns for stores, products, revenue and sold quantity. We’d like to do a groupwise calculation of prices (i.e. revenue/quantity) per store and per product. We could do this in a multi-step operation, but expressing it in terms of piping can make the code more readable. First we set the data:

In [195]: import numpy as np

In [196]: n = 1000

In [197]: df = pd.DataFrame({'Store': np.random.choice(['Store_1', 'Store_2'], n),
   .....:                    'Product': np.random.choice(['Product_1', 'Product_2', 'Product_3'], n),
   .....:                    'Revenue': (np.random.random(n)*50+10).round(2),
   .....:                    'Quantity': np.random.randint(1, 10, size=n)})
   .....: 

In [198]: df.head(2)
Out[198]: 
     Product  Quantity  Revenue    Store
0  Product_1         6    30.35  Store_2
1  Product_3         2    35.69  Store_2

Now, to find prices per store/product, we can simply do:

In [199]: (df.groupby(['Store', 'Product'])
   .....:    .pipe(lambda grp: grp.Revenue.sum()/grp.Quantity.sum())
   .....:    .unstack().round(2))
   .....: 
Out[199]: 
Product  Product_1  Product_2  Product_3
Store                                   
Store_1       6.93       6.82       7.15
Store_2       6.69       6.64       6.77

Piping can also be expressive when you want to deliver a grouped object to some arbitrary function, for example:

(df.groupby(['Store', 'Product']).pipe(report_func)

where report_func takes a GroupBy object and creates a report from that.

Examples

Regrouping by factor

Regroup columns of a DataFrame according to their sum, and sum the aggregated ones.

In [200]: df = pd.DataFrame({'a':[1,0,0], 'b':[0,1,0], 'c':[1,0,0], 'd':[2,3,4]})

In [201]: df
Out[201]: 
   a  b  c  d
0  1  0  1  2
1  0  1  0  3
2  0  0  0  4

In [202]: df.groupby(df.sum(), axis=1).sum()
Out[202]: 
   1  9
0  2  2
1  1  3
2  0  4

Multi-column factorization

By using .ngroup(), we can extract information about the groups in a way similar to factorize() (as described further in the reshaping API) but which applies naturally to multiple columns of mixed type and different sources. This can be useful as an intermediate categorical-like step in processing, when the relationships between the group rows are more important than their content, or as input to an algorithm which only accepts the integer encoding. (For more information about support in pandas for full categorical data, see the Categorical introduction and the API documentation.)

In [203]: dfg = pd.DataFrame({"A": [1, 1, 2, 3, 2], "B": list("aaaba")})

In [204]: dfg
Out[204]: 
   A  B
0  1  a
1  1  a
2  2  a
3  3  b
4  2  a

In [205]: dfg.groupby(["A", "B"]).ngroup()
Out[205]: 
0    0
1    0
2    1
3    2
4    1
dtype: int64

In [206]: dfg.groupby(["A", [0, 0, 0, 1, 1]]).ngroup()
Out[206]: 
0    0
1    0
2    1
3    3
4    2
dtype: int64

Groupby by Indexer to ‘resample’ data

Resampling produces new hypothetical samples (resamples) from already existing observed data or from a model that generates data. These new samples are similar to the pre-existing samples.

In order to resample to work on indices that are non-datetimelike, the following procedure can be utilized.

In the following examples, df.index // 5 returns a binary array which is used to determine what gets selected for the groupby operation.

Note

The below example shows how we can downsample by consolidation of samples into fewer samples. Here by using df.index // 5, we are aggregating the samples in bins. By applying std() function, we aggregate the information contained in many samples into a small subset of values which is their standard deviation thereby reducing the number of samples.

In [207]: df = pd.DataFrame(np.random.randn(10,2))

In [208]: df
Out[208]: 
          0         1
0  0.431670  0.882143
1 -0.026213 -1.941880
2 -1.106825 -0.667835
3  0.210712 -0.530195
4 -0.295191 -0.172722
5  0.638454  1.807622
6  1.008900  0.672822
7  0.770658  1.533002
8  0.576321 -0.819781
9 -1.302052  1.599477

In [209]: df.index // 5
Out[209]: Int64Index([0, 0, 0, 0, 0, 1, 1, 1, 1, 1], dtype='int64')

In [210]: df.groupby(df.index // 5).std()
Out[210]: 
          0         1
0  0.595843  1.015451
1  0.931952  1.084644

Returning a Series to propagate names

Group DataFrame columns, compute a set of metrics and return a named Series. The Series name is used as the name for the column index. This is especially useful in conjunction with reshaping operations such as stacking in which the column index name will be used as the name of the inserted column:

In [211]: df = pd.DataFrame({
   .....:          'a':  [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2],
   .....:          'b':  [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
   .....:          'c':  [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
   .....:          'd':  [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1],
   .....:          })
   .....: 

In [212]: def compute_metrics(x):
   .....:     result = {'b_sum': x['b'].sum(), 'c_mean': x['c'].mean()}
   .....:     return pd.Series(result, name='metrics')
   .....: 

In [213]: result = df.groupby('a').apply(compute_metrics)

In [214]: result
Out[214]: 
metrics  b_sum  c_mean
a                     
0          2.0     0.5
1          2.0     0.5
2          2.0     0.5

In [215]: result.stack()
Out[215]: 
a  metrics
0  b_sum      2.0
   c_mean     0.5
1  b_sum      2.0
   c_mean     0.5
2  b_sum      2.0
   c_mean     0.5
dtype: float64
Scroll To Top