Group By: split-apply-combine

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

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

Out of these, the split step is the most straightforward. In fact, in manysituations we may wish to split the data set into groups and do something withthose groups. In the apply step, we might wish to do one of thefollowing:

  • Aggregation: compute a summary statistic (or statistics) for eachgroup. Some examples:
  • Compute group sums or means.
  • Compute group sizes / counts.
  • Transformation: perform some group-specific computations and return alike-indexed object. Some examples:
  • Standardize data (zscore) within a group.
  • Filling NAs within groups with a value derived from each group.
  • Filtration: discard some groups, according to a group-wise computationthat evaluates True or False. Some examples:
  • Discard data that belongs to groups with only a few members.
  • Filter out data based on the group sum or mean.
  • Some combination of the above: GroupBy will examine the results of the applystep and try to return a sensibly combined result if it doesn’t fit intoeither of the above two categories.

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

  1. SELECT Column1, Column2, mean(Column3), sum(Column4)
  2. FROM SomeTable
  3. GROUP BY Column1, Column2

We aim to make operations like this natural and easy to express usingpandas. We’ll address each area of GroupBy functionality then provide somenon-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 ofgrouping is to provide a mapping of labels to group names. To create a GroupByobject (more on what the GroupBy object is later), you may do the following:

  1. In [1]: df = pd.DataFrame([('bird', 'Falconiformes', 389.0),
  2. ...: ('bird', 'Psittaciformes', 24.0),
  3. ...: ('mammal', 'Carnivora', 80.2),
  4. ...: ('mammal', 'Primates', np.nan),
  5. ...: ('mammal', 'Carnivora', 58)],
  6. ...: index=['falcon', 'parrot', 'lion', 'monkey', 'leopard'],
  7. ...: columns=('class', 'order', 'max_speed'))
  8. ...:
  9.  
  10. In [2]: df
  11. Out[2]:
  12. class order max_speed
  13. falcon bird Falconiformes 389.0
  14. parrot bird Psittaciformes 24.0
  15. lion mammal Carnivora 80.2
  16. monkey mammal Primates NaN
  17. leopard mammal Carnivora 58.0
  18.  
  19. # default is axis=0
  20. In [3]: grouped = df.groupby('class')
  21.  
  22. In [4]: grouped = df.groupby('order', axis='columns')
  23.  
  24. In [5]: grouped = df.groupby(['class', 'order'])

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 fordf.groupby(df['A']), but it makes life simpler.
  • For DataFrame objects, a string indicating an index level to be used togroup.
  • 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

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, aValueError will be raised.

  1. In [6]: df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
  2. ...: 'foo', 'bar', 'foo', 'foo'],
  3. ...: 'B': ['one', 'one', 'two', 'three',
  4. ...: 'two', 'two', 'one', 'three'],
  5. ...: 'C': np.random.randn(8),
  6. ...: 'D': np.random.randn(8)})
  7. ...:
  8.  
  9. In [7]: df
  10. Out[7]:
  11. A B C D
  12. 0 foo one 0.469112 -0.861849
  13. 1 bar one -0.282863 -2.104569
  14. 2 foo two -1.509059 -0.494929
  15. 3 bar three -1.135632 1.071804
  16. 4 foo two 1.212112 0.721555
  17. 5 bar two -0.173215 -0.706771
  18. 6 foo one 0.119209 -1.039575
  19. 7 foo three -1.044236 0.271860

On a DataFrame, we obtain a GroupBy object by calling groupby().We could naturally group by either the A or B columns, or both:

  1. In [8]: grouped = df.groupby('A')
  2.  
  3. In [9]: grouped = df.groupby(['A', 'B'])

New in version 0.24.

If we also have a MultiIndex on columns A and B, we can group by allbut the specified columns

  1. In [10]: df2 = df.set_index(['A', 'B'])
  2.  
  3. In [11]: grouped = df2.groupby(level=df2.index.names.difference(['B']))
  4.  
  5. In [12]: grouped.sum()
  6. Out[12]:
  7. C D
  8. A
  9. bar -1.591710 -1.739537
  10. foo -0.752861 -1.402938

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

  1. In [13]: def get_letter_type(letter):
  2. ....: if letter.lower() in 'aeiou':
  3. ....: return 'vowel'
  4. ....: else:
  5. ....: return 'consonant'
  6. ....:
  7.  
  8. In [14]: grouped = df.groupby(get_letter_type, axis=1)

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

  1. In [15]: lst = [1, 2, 3, 1, 2, 3]
  2.  
  3. In [16]: s = pd.Series([1, 2, 3, 10, 20, 30], lst)
  4.  
  5. In [17]: grouped = s.groupby(level=0)
  6.  
  7. In [18]: grouped.first()
  8. Out[18]:
  9. 1 1
  10. 2 2
  11. 3 3
  12. dtype: int64
  13.  
  14. In [19]: grouped.last()
  15. Out[19]:
  16. 1 10
  17. 2 20
  18. 3 30
  19. dtype: int64
  20.  
  21. In [20]: grouped.sum()
  22. Out[20]:
  23. 1 11
  24. 2 22
  25. 3 33
  26. dtype: int64

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

Note

Many kinds of complicated data manipulations can be expressed in terms ofGroupBy operations (though can’t be guaranteed to be the mostefficient). 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:

  1. In [21]: df2 = pd.DataFrame({'X': ['B', 'B', 'A', 'A'], 'Y': [1, 2, 3, 4]})
  2.  
  3. In [22]: df2.groupby(['X']).sum()
  4. Out[22]:
  5. Y
  6. X
  7. A 7
  8. B 3
  9.  
  10. In [23]: df2.groupby(['X'], sort=False).sum()
  11. Out[23]:
  12. Y
  13. X
  14. B 3
  15. 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:

  1. In [24]: df3 = pd.DataFrame({'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]})
  2.  
  3. In [25]: df3.groupby(['X']).get_group('A')
  4. Out[25]:
  5. X Y
  6. 0 A 1
  7. 2 A 3
  8.  
  9. In [26]: df3.groupby(['X']).get_group('B')
  10. Out[26]:
  11. X Y
  12. 1 B 4
  13. 3 B 2

GroupBy object attributes

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

  1. In [27]: df.groupby('A').groups
  2. Out[27]:
  3. {'bar': Int64Index([1, 3, 5], dtype='int64'),
  4. 'foo': Int64Index([0, 2, 4, 6, 7], dtype='int64')}
  5.  
  6. In [28]: df.groupby(get_letter_type, axis=1).groups
  7. Out[28]:
  8. {'consonant': Index(['B', 'C', 'D'], dtype='object'),
  9. 'vowel': Index(['A'], dtype='object')}

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

  1. In [29]: grouped = df.groupby(['A', 'B'])
  2.  
  3. In [30]: grouped.groups
  4. Out[30]:
  5. {('bar', 'one'): Int64Index([1], dtype='int64'),
  6. ('bar', 'three'): Int64Index([3], dtype='int64'),
  7. ('bar', 'two'): Int64Index([5], dtype='int64'),
  8. ('foo', 'one'): Int64Index([0, 6], dtype='int64'),
  9. ('foo', 'three'): Int64Index([7], dtype='int64'),
  10. ('foo', 'two'): Int64Index([2, 4], dtype='int64')}
  11.  
  12. In [31]: len(grouped)
  13. Out[31]: 6

GroupBy will tab complete column names (and other attributes):

  1. In [32]: df
  2. Out[32]:
  3. height weight gender
  4. 2000-01-01 42.849980 157.500553 male
  5. 2000-01-02 49.607315 177.340407 male
  6. 2000-01-03 56.293531 171.524640 male
  7. 2000-01-04 48.421077 144.251986 female
  8. 2000-01-05 46.556882 152.526206 male
  9. 2000-01-06 68.448851 168.272968 female
  10. 2000-01-07 70.757698 136.431469 male
  11. 2000-01-08 58.909500 176.499753 female
  12. 2000-01-09 76.435631 174.094104 female
  13. 2000-01-10 45.306120 177.540920 male
  14.  
  15. In [33]: gb = df.groupby('gender')
  1. In [34]: gb.<TAB> # noqa: E225, E999
  2. 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
  3. 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
  4. 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 quitenatural to group by one of the levels of the hierarchy.

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

  1. In [35]: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
  2. ....: ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
  3. ....:
  4.  
  5. In [36]: index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])
  6.  
  7. In [37]: s = pd.Series(np.random.randn(8), index=index)
  8.  
  9. In [38]: s
  10. Out[38]:
  11. first second
  12. bar one -0.919854
  13. two -0.042379
  14. baz one 1.247642
  15. two -0.009920
  16. foo one 0.290213
  17. two 0.495767
  18. qux one 0.362949
  19. two 1.548106
  20. dtype: float64

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

  1. In [39]: grouped = s.groupby(level=0)
  2.  
  3. In [40]: grouped.sum()
  4. Out[40]:
  5. first
  6. bar -0.962232
  7. baz 1.237723
  8. foo 0.785980
  9. qux 1.911055
  10. dtype: float64

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

  1. In [41]: s.groupby(level='second').sum()
  2. Out[41]:
  3. second
  4. one 0.980950
  5. two 1.991575
  6. dtype: float64

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

  1. In [42]: s.sum(level='second')
  2. Out[42]:
  3. second
  4. one 0.980950
  5. two 1.991575
  6. dtype: float64

Grouping with multiple levels is supported.

  1. In [43]: s
  2. Out[43]:
  3. first second third
  4. bar doo one -1.131345
  5. two -0.089329
  6. baz bee one 0.337863
  7. two -0.945867
  8. foo bop one -0.932132
  9. two 1.956030
  10. qux bop one 0.017587
  11. two -0.016692
  12. dtype: float64
  13.  
  14. In [44]: s.groupby(level=['first', 'second']).sum()
  15. Out[44]:
  16. first second
  17. bar doo -1.220674
  18. baz bee -0.608004
  19. foo bop 1.023898
  20. qux bop 0.000895
  21. dtype: float64

New in version 0.20.

Index level names may be supplied as keys.

  1. In [45]: s.groupby(['first', 'second']).sum()
  2. Out[45]:
  3. first second
  4. bar doo -1.220674
  5. baz bee -0.608004
  6. foo bop 1.023898
  7. qux bop 0.000895
  8. 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 byspecifying the column names as strings and the index levels as pd.Grouperobjects.

  1. In [46]: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
  2. ....: ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
  3. ....:
  4.  
  5. In [47]: index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])
  6.  
  7. In [48]: df = pd.DataFrame({'A': [1, 1, 1, 1, 2, 2, 3, 3],
  8. ....: 'B': np.arange(8)},
  9. ....: index=index)
  10. ....:
  11.  
  12. In [49]: df
  13. Out[49]:
  14. A B
  15. first second
  16. bar one 1 0
  17. two 1 1
  18. baz one 1 2
  19. two 1 3
  20. foo one 2 4
  21. two 2 5
  22. qux one 3 6
  23. two 3 7

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

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

Index levels may also be specified by name.

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

New in version 0.20.

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

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

DataFrame column selection in GroupBy

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

  1. In [53]: grouped = df.groupby(['A'])
  2.  
  3. In [54]: grouped_C = grouped['C']
  4.  
  5. In [55]: grouped_D = grouped['D']

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

  1. In [56]: df['C'].groupby(df['A'])
  2. Out[56]: <pandas.core.groupby.generic.SeriesGroupBy object at 0x7f45270d68d0>

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

Iterating through groups

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

  1. In [57]: grouped = df.groupby('A')
  2.  
  3. In [58]: for name, group in grouped:
  4. ....: print(name)
  5. ....: print(group)
  6. ....:
  7. bar
  8. A B C D
  9. 1 bar one 0.254161 1.511763
  10. 3 bar three 0.215897 -0.990582
  11. 5 bar two -0.077118 1.211526
  12. foo
  13. A B C D
  14. 0 foo one -0.575247 1.346061
  15. 2 foo two -1.143704 1.627081
  16. 4 foo two 1.193555 -0.441652
  17. 6 foo one -0.408530 0.268520
  18. 7 foo three -0.862495 0.024580

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

  1. In [59]: for name, group in df.groupby(['A', 'B']):
  2. ....: print(name)
  3. ....: print(group)
  4. ....:
  5. ('bar', 'one')
  6. A B C D
  7. 1 bar one 0.254161 1.511763
  8. ('bar', 'three')
  9. A B C D
  10. 3 bar three 0.215897 -0.990582
  11. ('bar', 'two')
  12. A B C D
  13. 5 bar two -0.077118 1.211526
  14. ('foo', 'one')
  15. A B C D
  16. 0 foo one -0.575247 1.346061
  17. 6 foo one -0.408530 0.268520
  18. ('foo', 'three')
  19. A B C D
  20. 7 foo three -0.862495 0.02458
  21. ('foo', 'two')
  22. A B C D
  23. 2 foo two -1.143704 1.627081
  24. 4 foo two 1.193555 -0.441652

See Iterating through groups.

Selecting a group

A single group can be selected usingget_group():

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

Or for an object grouped on multiple columns:

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

Aggregation

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

An obvious one is aggregation via theaggregate() or equivalentlyagg() method:

  1. In [62]: grouped = df.groupby('A')
  2.  
  3. In [63]: grouped.aggregate(np.sum)
  4. Out[63]:
  5. C D
  6. A
  7. bar 0.392940 1.732707
  8. foo -1.796421 2.824590
  9.  
  10. In [64]: grouped = df.groupby(['A', 'B'])
  11.  
  12. In [65]: grouped.aggregate(np.sum)
  13. Out[65]:
  14. C D
  15. A B
  16. bar one 0.254161 1.511763
  17. three 0.215897 -0.990582
  18. two -0.077118 1.211526
  19. foo one -0.983776 1.614581
  20. three -0.862495 0.024580
  21. two 0.049851 1.185429

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

  1. In [66]: grouped = df.groupby(['A', 'B'], as_index=False)
  2.  
  3. In [67]: grouped.aggregate(np.sum)
  4. Out[67]:
  5. A B C D
  6. 0 bar one 0.254161 1.511763
  7. 1 bar three 0.215897 -0.990582
  8. 2 bar two -0.077118 1.211526
  9. 3 foo one -0.983776 1.614581
  10. 4 foo three -0.862495 0.024580
  11. 5 foo two 0.049851 1.185429
  12.  
  13. In [68]: df.groupby('A', as_index=False).sum()
  14. Out[68]:
  15. A C D
  16. 0 bar 0.392940 1.732707
  17. 1 foo -1.796421 2.824590

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

  1. In [69]: df.groupby(['A', 'B']).sum().reset_index()
  2. Out[69]:
  3. A B C D
  4. 0 bar one 0.254161 1.511763
  5. 1 bar three 0.215897 -0.990582
  6. 2 bar two -0.077118 1.211526
  7. 3 foo one -0.983776 1.614581
  8. 4 foo three -0.862495 0.024580
  9. 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 whoseindex are the group names and whose values are the sizes of each group.

  1. In [70]: grouped.size()
  2. Out[70]:
  3. A B
  4. bar one 1
  5. three 1
  6. two 1
  7. foo one 2
  8. three 1
  9. two 2
  10. dtype: int64
  1. In [71]: grouped.describe()
  2. Out[71]:
  3. C D
  4. count mean std min 25% 50% 75% max count mean std min 25% 50% 75% max
  5. 0 1.0 0.254161 NaN 0.254161 0.254161 0.254161 0.254161 0.254161 1.0 1.511763 NaN 1.511763 1.511763 1.511763 1.511763 1.511763
  6. 1 1.0 0.215897 NaN 0.215897 0.215897 0.215897 0.215897 0.215897 1.0 -0.990582 NaN -0.990582 -0.990582 -0.990582 -0.990582 -0.990582
  7. 2 1.0 -0.077118 NaN -0.077118 -0.077118 -0.077118 -0.077118 -0.077118 1.0 1.211526 NaN 1.211526 1.211526 1.211526 1.211526 1.211526
  8. 3 2.0 -0.491888 0.117887 -0.575247 -0.533567 -0.491888 -0.450209 -0.408530 2.0 0.807291 0.761937 0.268520 0.537905 0.807291 1.076676 1.346061
  9. 4 1.0 -0.862495 NaN -0.862495 -0.862495 -0.862495 -0.862495 -0.862495 1.0 0.024580 NaN 0.024580 0.024580 0.024580 0.024580 0.024580
  10. 5 2.0 0.024925 1.652692 -1.143704 -0.559389 0.024925 0.609240 1.193555 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 overif they are named columns, when as_index=True, the default. The grouped columns willbe the indices of the returned object.

Passing asindex=False will return the groups that you are aggregating over, if they arenamed _columns.

Aggregating functions are the ones that reduce the dimension of the returned objects.Some common aggregating functions are tabulated below:

FunctionDescription
mean()Compute mean of groups
sum()Compute sum of group values
size()Compute group sizes
count()Compute count of group
std()Standard deviation of groups
var()Compute variance of groups
sem()Standard error of the mean of groups
describe()Generates descriptive statistics
first()Compute first of group values
last()Compute last of group values
nth()Take nth value, or a subset if n is a list
min()Compute min of group values
max()Compute max of group values

The aggregating functions above will exclude NA values. Any function whichreduces a Series to a scalar value is an aggregation function and will work,a trivial example is df.groupby('A').agg(lambda ser: 1). Note thatnth() can act as a reducer or afilter, see here.

Applying multiple functions at once

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

  1. In [72]: grouped = df.groupby('A')
  2.  
  3. In [73]: grouped['C'].agg([np.sum, np.mean, np.std])
  4. Out[73]:
  5. sum mean std
  6. A
  7. bar 0.392940 0.130980 0.181231
  8. foo -1.796421 -0.359284 0.912265

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

  1. In [74]: grouped.agg([np.sum, np.mean, np.std])
  2. Out[74]:
  3. C D
  4. sum mean std sum mean std
  5. A
  6. bar 0.392940 0.130980 0.181231 1.732707 0.577569 1.366330
  7. foo -1.796421 -0.359284 0.912265 2.824590 0.564918 0.884785

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

  1. In [75]: (grouped['C'].agg([np.sum, np.mean, np.std])
  2. ....: .rename(columns={'sum': 'foo',
  3. ....: 'mean': 'bar',
  4. ....: 'std': 'baz'}))
  5. ....:
  6. Out[75]:
  7. foo bar baz
  8. A
  9. bar 0.392940 0.130980 0.181231
  10. foo -1.796421 -0.359284 0.912265

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

  1. In [76]: (grouped.agg([np.sum, np.mean, np.std])
  2. ....: .rename(columns={'sum': 'foo',
  3. ....: 'mean': 'bar',
  4. ....: 'std': 'baz'}))
  5. ....:
  6. Out[76]:
  7. C D
  8. foo bar baz foo bar baz
  9. A
  10. bar 0.392940 0.130980 0.181231 1.732707 0.577569 1.366330
  11. foo -1.796421 -0.359284 0.912265 2.824590 0.564918 0.884785

Note

In general, the output column names should be unique. You can’t applythe same function (or two functions with the same name) to the samecolumn.

  1. In [77]: grouped['C'].agg(['sum', 'sum'])

SpecificationError Traceback (most recent call last)<ipython-input-77-7be02859f395> in <module>——> 1 grouped['C'].agg(['sum', 'sum'])

/pandas/pandas/core/groupby/generic.py in aggregate(self, func_or_funcs, args, *kwargs) 849 # but not the class list / tuple itself. 850 func_or_funcs = _maybe_mangle_lambdas(func_or_funcs)—> 851 ret = self._aggregate_multiple_funcs(func_or_funcs, (_level or 0) + 1) 852 if relabeling: 853 ret.columns = columns

/pandas/pandas/core/groupby/generic.py in _aggregate_multiple_funcs(self, arg, _level) 919 raise SpecificationError( 920 "Function names must be unique, found multiple named "—> 921 "{}".format(name) 922 ) 923

SpecificationError: Function names must be unique, found multiple named sum

Pandas does allow you to provide multiple lambdas. In this case, pandaswill mangle the name of the (nameless) lambda functions, appending _<i>to each subsequent lambda.

  1. In [78]: grouped['C'].agg([lambda x: x.max() - x.min(),
  2. ....: lambda x: x.median() - x.mean()])
  3. ....:
  4. Out[78]:
  5. <lambda_0> <lambda_1>
  6. A
  7. bar 0.331279 0.084917
  8. foo 2.337259 -0.215962

Named aggregation

New in version 0.25.0.

To support column-specific aggregation with control over the output column names, pandasaccepts the special syntax in GroupBy.agg(), known as “named aggregation”, where

  • The keywords are the output column names
  • The values are tuples whose first element is the column to selectand the second element is the aggregation to apply to that column. Pandasprovides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc']to make it clearer what the arguments are. As usual, the aggregation canbe a callable or a string alias.
  1. In [79]: animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
  2. ....: 'height': [9.1, 6.0, 9.5, 34.0],
  3. ....: 'weight': [7.9, 7.5, 9.9, 198.0]})
  4. ....:
  5.  
  6. In [80]: animals
  7. Out[80]:
  8. kind height weight
  9. 0 cat 9.1 7.9
  10. 1 dog 6.0 7.5
  11. 2 cat 9.5 9.9
  12. 3 dog 34.0 198.0
  13.  
  14. In [81]: animals.groupby("kind").agg(
  15. ....: min_height=pd.NamedAgg(column='height', aggfunc='min'),
  16. ....: max_height=pd.NamedAgg(column='height', aggfunc='max'),
  17. ....: average_weight=pd.NamedAgg(column='weight', aggfunc=np.mean),
  18. ....: )
  19. ....:
  20. Out[81]:
  21. min_height max_height average_weight
  22. kind
  23. cat 9.1 9.5 8.90
  24. dog 6.0 34.0 102.75

pandas.NamedAgg is just a namedtuple. Plain tuples are allowed as well.

  1. In [82]: animals.groupby("kind").agg(
  2. ....: min_height=('height', 'min'),
  3. ....: max_height=('height', 'max'),
  4. ....: average_weight=('weight', np.mean),
  5. ....: )
  6. ....:
  7. Out[82]:
  8. min_height max_height average_weight
  9. kind
  10. cat 9.1 9.5 8.90
  11. dog 6.0 34.0 102.75

If your desired output column names are not valid python keywords, construct a dictionaryand unpack the keyword arguments

  1. In [83]: animals.groupby("kind").agg(**{
  2. ....: 'total weight': pd.NamedAgg(column='weight', aggfunc=sum),
  3. ....: })
  4. ....:
  5. Out[83]:
  6. total weight
  7. kind
  8. cat 17.8
  9. dog 205.5

Additional keyword arguments are not passed through to the aggregation functions. Only pairsof (column, aggfunc) should be passed as **kwargs. If your aggregation functionsrequires additional arguments, partially apply them with functools.partial().

Note

For Python 3.5 and earlier, the order of **kwargs in a functions was notpreserved. This means that the output column ordering would not beconsistent. To ensure consistent ordering, the keys (and so output columns)will always be sorted for Python 3.5.

Named aggregation is also valid for Series groupby aggregations. In this case there’sno column selection, so the values are just the functions.

  1. In [84]: animals.groupby("kind").height.agg(
  2. ....: min_height='min',
  3. ....: max_height='max',
  4. ....: )
  5. ....:
  6. Out[84]:
  7. min_height max_height
  8. kind
  9. cat 9.1 9.5
  10. dog 6.0 34.0

Applying different functions to DataFrame columns

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

  1. In [85]: grouped.agg({'C': np.sum,
  2. ....: 'D': lambda x: np.std(x, ddof=1)})
  3. ....:
  4. Out[85]:
  5. C D
  6. A
  7. bar 0.392940 1.366330
  8. foo -1.796421 0.884785

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

  1. In [86]: grouped.agg({'C': 'sum', 'D': 'std'})
  2. Out[86]:
  3. C D
  4. A
  5. bar 0.392940 1.366330
  6. foo -1.796421 0.884785

Cython-optimized aggregation functions

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

  1. In [87]: df.groupby('A').sum()
  2. Out[87]:
  3. C D
  4. A
  5. bar 0.392940 1.732707
  6. foo -1.796421 2.824590
  7.  
  8. In [88]: df.groupby(['A', 'B']).mean()
  9. Out[88]:
  10. C D
  11. A B
  12. bar one 0.254161 1.511763
  13. three 0.215897 -0.990582
  14. two -0.077118 1.211526
  15. foo one -0.491888 0.807291
  16. three -0.862495 0.024580
  17. two 0.024925 0.592714

Of course sum and mean are implemented on pandas objects, so the abovecode 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 orbroadcastable 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 tothe first group chunk using chunk.apply.
  • Not perform in-place operations on the group chunk. Group chunks shouldbe treated as immutable, and changes to a group chunk may produce unexpectedresults. 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, afast path is used starting from the second chunk.

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

  1. In [89]: index = pd.date_range('10/1/1999', periods=1100)
  2.  
  3. In [90]: ts = pd.Series(np.random.normal(0.5, 2, 1100), index)
  4.  
  5. In [91]: ts = ts.rolling(window=100, min_periods=100).mean().dropna()
  6.  
  7. In [92]: ts.head()
  8. Out[92]:
  9. 2000-01-08 0.779333
  10. 2000-01-09 0.778852
  11. 2000-01-10 0.786476
  12. 2000-01-11 0.782797
  13. 2000-01-12 0.798110
  14. Freq: D, dtype: float64
  15.  
  16. In [93]: ts.tail()
  17. Out[93]:
  18. 2002-09-30 0.660294
  19. 2002-10-01 0.631095
  20. 2002-10-02 0.673601
  21. 2002-10-03 0.709213
  22. 2002-10-04 0.719369
  23. Freq: D, dtype: float64
  24.  
  25. In [94]: transformed = (ts.groupby(lambda x: x.year)
  26. ....: .transform(lambda x: (x - x.mean()) / x.std()))
  27. ....:

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

  1. # Original Data
  2. In [95]: grouped = ts.groupby(lambda x: x.year)
  3.  
  4. In [96]: grouped.mean()
  5. Out[96]:
  6. 2000 0.442441
  7. 2001 0.526246
  8. 2002 0.459365
  9. dtype: float64
  10.  
  11. In [97]: grouped.std()
  12. Out[97]:
  13. 2000 0.131752
  14. 2001 0.210945
  15. 2002 0.128753
  16. dtype: float64
  17.  
  18. # Transformed Data
  19. In [98]: grouped_trans = transformed.groupby(lambda x: x.year)
  20.  
  21. In [99]: grouped_trans.mean()
  22. Out[99]:
  23. 2000 1.168208e-15
  24. 2001 1.454544e-15
  25. 2002 1.726657e-15
  26. dtype: float64
  27.  
  28. In [100]: grouped_trans.std()
  29. Out[100]:
  30. 2000 1.0
  31. 2001 1.0
  32. 2002 1.0
  33. dtype: float64

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

  1. In [101]: compare = pd.DataFrame({'Original': ts, 'Transformed': transformed})
  2.  
  3. In [102]: compare.plot()
  4. Out[102]: <matplotlib.axes._subplots.AxesSubplot at 0x7f45292f6910>

../_images/groupby_transform_plot.pngTransformation functions that have lower dimension outputs are broadcast tomatch the shape of the input array.

  1. In [103]: ts.groupby(lambda x: x.year).transform(lambda x: x.max() - x.min())
  2. Out[103]:
  3. 2000-01-08 0.623893
  4. 2000-01-09 0.623893
  5. 2000-01-10 0.623893
  6. 2000-01-11 0.623893
  7. 2000-01-12 0.623893
  8. ...
  9. 2002-09-30 0.558275
  10. 2002-10-01 0.558275
  11. 2002-10-02 0.558275
  12. 2002-10-03 0.558275
  13. 2002-10-04 0.558275
  14. Freq: D, Length: 1001, dtype: float64

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

  1. In [104]: max = ts.groupby(lambda x: x.year).transform('max')
  2.  
  3. In [105]: min = ts.groupby(lambda x: x.year).transform('min')
  4.  
  5. In [106]: max - min
  6. Out[106]:
  7. 2000-01-08 0.623893
  8. 2000-01-09 0.623893
  9. 2000-01-10 0.623893
  10. 2000-01-11 0.623893
  11. 2000-01-12 0.623893
  12. ...
  13. 2002-09-30 0.558275
  14. 2002-10-01 0.558275
  15. 2002-10-02 0.558275
  16. 2002-10-03 0.558275
  17. 2002-10-04 0.558275
  18. Freq: D, Length: 1001, dtype: float64

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

  1. In [107]: data_df
  2. Out[107]:
  3. A B C
  4. 0 1.539708 -1.166480 0.533026
  5. 1 1.302092 -0.505754 NaN
  6. 2 -0.371983 1.104803 -0.651520
  7. 3 -1.309622 1.118697 -1.161657
  8. 4 -1.924296 0.396437 0.812436
  9. .. ... ... ...
  10. 995 -0.093110 0.683847 -0.774753
  11. 996 -0.185043 1.438572 NaN
  12. 997 -0.394469 -0.642343 0.011374
  13. 998 -1.174126 1.857148 NaN
  14. 999 0.234564 0.517098 0.393534
  15.  
  16. [1000 rows x 3 columns]
  17.  
  18. In [108]: countries = np.array(['US', 'UK', 'GR', 'JP'])
  19.  
  20. In [109]: key = countries[np.random.randint(0, 4, 1000)]
  21.  
  22. In [110]: grouped = data_df.groupby(key)
  23.  
  24. # Non-NA count in each group
  25. In [111]: grouped.count()
  26. Out[111]:
  27. A B C
  28. GR 209 217 189
  29. JP 240 255 217
  30. UK 216 231 193
  31. US 239 250 217
  32.  
  33. In [112]: transformed = grouped.transform(lambda x: x.fillna(x.mean()))

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

  1. In [113]: grouped_trans = transformed.groupby(key)
  2.  
  3. In [114]: grouped.mean() # original group means
  4. Out[114]:
  5. A B C
  6. GR -0.098371 -0.015420 0.068053
  7. JP 0.069025 0.023100 -0.077324
  8. UK 0.034069 -0.052580 -0.116525
  9. US 0.058664 -0.020399 0.028603
  10.  
  11. In [115]: grouped_trans.mean() # transformation did not change group means
  12. Out[115]:
  13. A B C
  14. GR -0.098371 -0.015420 0.068053
  15. JP 0.069025 0.023100 -0.077324
  16. UK 0.034069 -0.052580 -0.116525
  17. US 0.058664 -0.020399 0.028603
  18.  
  19. In [116]: grouped.count() # original has some missing data points
  20. Out[116]:
  21. A B C
  22. GR 209 217 189
  23. JP 240 255 217
  24. UK 216 231 193
  25. US 239 250 217
  26.  
  27. In [117]: grouped_trans.count() # counts after transformation
  28. Out[117]:
  29. A B C
  30. GR 228 228 228
  31. JP 267 267 267
  32. UK 247 247 247
  33. US 258 258 258
  34.  
  35. In [118]: grouped_trans.size() # Verify non-NA count equals group size
  36. Out[118]:
  37. GR 228
  38. JP 267
  39. UK 247
  40. US 258
  41. dtype: int64

Note

Some functions will automatically transform the input when applied to aGroupBy object, but 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..

  1. In [119]: grouped.ffill()
  2. Out[119]:
  3. A B C
  4. 0 1.539708 -1.166480 0.533026
  5. 1 1.302092 -0.505754 0.533026
  6. 2 -0.371983 1.104803 -0.651520
  7. 3 -1.309622 1.118697 -1.161657
  8. 4 -1.924296 0.396437 0.812436
  9. .. ... ... ...
  10. 995 -0.093110 0.683847 -0.774753
  11. 996 -0.185043 1.438572 -0.774753
  12. 997 -0.394469 -0.642343 0.011374
  13. 998 -1.174126 1.857148 -0.774753
  14. 999 0.234564 0.517098 0.393534
  15.  
  16. [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 groupbylevel used to require the application of helper functions. However,now it is possible to use resample(), expanding() androlling() as methods on groupbys.

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

  1. In [120]: df_re = pd.DataFrame({'A': [1] * 10 + [5] * 10,
  2. .....: 'B': np.arange(20)})
  3. .....:
  4.  
  5. In [121]: df_re
  6. Out[121]:
  7. A B
  8. 0 1 0
  9. 1 1 1
  10. 2 1 2
  11. 3 1 3
  12. 4 1 4
  13. .. .. ..
  14. 15 5 15
  15. 16 5 16
  16. 17 5 17
  17. 18 5 18
  18. 19 5 19
  19.  
  20. [20 rows x 2 columns]
  21.  
  22. In [122]: df_re.groupby('A').rolling(4).B.mean()
  23. Out[122]:
  24. A
  25. 1 0 NaN
  26. 1 NaN
  27. 2 NaN
  28. 3 1.5
  29. 4 2.5
  30. ...
  31. 5 15 13.5
  32. 16 14.5
  33. 17 15.5
  34. 18 16.5
  35. 19 17.5
  36. Name: B, Length: 20, dtype: float64

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

  1. In [123]: df_re.groupby('A').expanding().sum()
  2. Out[123]:
  3. A B
  4. A
  5. 1 0 1.0 0.0
  6. 1 2.0 1.0
  7. 2 3.0 3.0
  8. 3 4.0 6.0
  9. 4 5.0 10.0
  10. ... ... ...
  11. 5 15 30.0 75.0
  12. 16 35.0 91.0
  13. 17 40.0 108.0
  14. 18 45.0 126.0
  15. 19 50.0 145.0
  16.  
  17. [20 rows x 2 columns]

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

  1. In [124]: df_re = pd.DataFrame({'date': pd.date_range(start='2016-01-01', periods=4,
  2. .....: freq='W'),
  3. .....: 'group': [1, 1, 2, 2],
  4. .....: 'val': [5, 6, 7, 8]}).set_index('date')
  5. .....:
  6.  
  7. In [125]: df_re
  8. Out[125]:
  9. group val
  10. date
  11. 2016-01-03 1 5
  12. 2016-01-10 1 6
  13. 2016-01-17 2 7
  14. 2016-01-24 2 8
  15.  
  16. In [126]: df_re.groupby('group').resample('1D').ffill()
  17. Out[126]:
  18. group val
  19. group date
  20. 1 2016-01-03 1 5
  21. 2016-01-04 1 5
  22. 2016-01-05 1 5
  23. 2016-01-06 1 5
  24. 2016-01-07 1 5
  25. ... ... ...
  26. 2 2016-01-20 2 7
  27. 2016-01-21 2 7
  28. 2016-01-22 2 7
  29. 2016-01-23 2 7
  30. 2016-01-24 2 8
  31.  
  32. [16 rows x 2 columns]

Filtration

The filter method returns a subset of the original object. Suppose wewant to take only elements that belong to groups with a group sum greaterthan 2.

  1. In [127]: sf = pd.Series([1, 1, 2, 3, 3, 3])
  2.  
  3. In [128]: sf.groupby(sf).filter(lambda x: x.sum() > 2)
  4. Out[128]:
  5. 3 3
  6. 4 3
  7. 5 3
  8. dtype: int64

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

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

  1. In [129]: dff = pd.DataFrame({'A': np.arange(8), 'B': list('aabbbbcc')})
  2.  
  3. In [130]: dff.groupby('B').filter(lambda x: len(x) > 2)
  4. Out[130]:
  5. A B
  6. 2 2 b
  7. 3 3 b
  8. 4 4 b
  9. 5 5 b

Alternatively, instead of dropping the offending groups, we can return alike-indexed objects where the groups that do not pass the filter are filledwith NaNs.

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

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

  1. In [132]: dff['C'] = np.arange(8)
  2.  
  3. In [133]: dff.groupby('B').filter(lambda x: len(x['C']) > 2)
  4. Out[133]:
  5. A B C
  6. 2 2 b 2
  7. 3 3 b 3
  8. 4 4 b 4
  9. 5 5 b 5

Note

Some functions when applied to a groupby object will act as a filter on the input, returninga 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.

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

Dispatching to instance methods

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

  1. In [135]: grouped = df.groupby('A')
  2.  
  3. In [136]: grouped.agg(lambda x: x.std())
  4. Out[136]:
  5. C D
  6. A
  7. bar 0.181231 1.366330
  8. foo 0.912265 0.884785

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

  1. In [137]: grouped.std()
  2. Out[137]:
  3. C D
  4. A
  5. bar 0.181231 1.366330
  6. foo 0.912265 0.884785

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

  1. In [138]: tsdf = pd.DataFrame(np.random.randn(1000, 3),
  2. .....: index=pd.date_range('1/1/2000', periods=1000),
  3. .....: columns=['A', 'B', 'C'])
  4. .....:
  5.  
  6. In [139]: tsdf.iloc[::2] = np.nan
  7.  
  8. In [140]: grouped = tsdf.groupby(lambda x: x.year)
  9.  
  10. In [141]: grouped.fillna(method='pad')
  11. Out[141]:
  12. A B C
  13. 2000-01-01 NaN NaN NaN
  14. 2000-01-02 -0.353501 -0.080957 -0.876864
  15. 2000-01-03 -0.353501 -0.080957 -0.876864
  16. 2000-01-04 0.050976 0.044273 -0.559849
  17. 2000-01-05 0.050976 0.044273 -0.559849
  18. ... ... ... ...
  19. 2002-09-22 0.005011 0.053897 -1.026922
  20. 2002-09-23 0.005011 0.053897 -1.026922
  21. 2002-09-24 -0.456542 -1.849051 1.559856
  22. 2002-09-25 -0.456542 -1.849051 1.559856
  23. 2002-09-26 1.123162 0.354660 1.128135
  24.  
  25. [1000 rows x 3 columns]

In this example, we chopped the collection of time series into yearly chunksthen independently called fillna on thegroups.

The nlargest and nsmallest methods work on Series style groupbys:

  1. In [142]: s = pd.Series([9, 8, 7, 5, 19, 1, 4.2, 3.3])
  2.  
  3. In [143]: g = pd.Series(list('abababab'))
  4.  
  5. In [144]: gb = s.groupby(g)
  6.  
  7. In [145]: gb.nlargest(3)
  8. Out[145]:
  9. a 4 19.0
  10. 0 9.0
  11. 2 7.0
  12. b 1 8.0
  13. 3 5.0
  14. 7 3.3
  15. dtype: float64
  16.  
  17. In [146]: gb.nsmallest(3)
  18. Out[146]:
  19. a 6 4.2
  20. 2 7.0
  21. 0 9.0
  22. b 5 1.0
  23. 7 3.3
  24. 3 5.0
  25. dtype: float64

Flexible apply

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

  1. In [147]: df
  2. Out[147]:
  3. A B C D
  4. 0 foo one -0.575247 1.346061
  5. 1 bar one 0.254161 1.511763
  6. 2 foo two -1.143704 1.627081
  7. 3 bar three 0.215897 -0.990582
  8. 4 foo two 1.193555 -0.441652
  9. 5 bar two -0.077118 1.211526
  10. 6 foo one -0.408530 0.268520
  11. 7 foo three -0.862495 0.024580
  12.  
  13. In [148]: grouped = df.groupby('A')
  14.  
  15. # could also just call .describe()
  16. In [149]: grouped['C'].apply(lambda x: x.describe())
  17. Out[149]:
  18. A
  19. bar count 3.000000
  20. mean 0.130980
  21. std 0.181231
  22. min -0.077118
  23. 25% 0.069390
  24. ...
  25. foo min -1.143704
  26. 25% -0.862495
  27. 50% -0.575247
  28. 75% -0.408530
  29. max 1.193555
  30. Name: C, Length: 16, dtype: float64

The dimension of the returned result can also change:

  1. In [150]: grouped = df.groupby('A')['C']
  2.  
  3. In [151]: def f(group):
  4. .....: return pd.DataFrame({'original': group,
  5. .....: 'demeaned': group - group.mean()})
  6. .....:
  7.  
  8. In [152]: grouped.apply(f)
  9. Out[152]:
  10. original demeaned
  11. 0 -0.575247 -0.215962
  12. 1 0.254161 0.123181
  13. 2 -1.143704 -0.784420
  14. 3 0.215897 0.084917
  15. 4 1.193555 1.552839
  16. 5 -0.077118 -0.208098
  17. 6 -0.408530 -0.049245
  18. 7 -0.862495 -0.503211

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:

  1. In [153]: def f(x):
  2. .....: return pd.Series([x, x ** 2], index=['x', 'x^2'])
  3. .....:
  4.  
  5. In [154]: s = pd.Series(np.random.rand(5))
  6.  
  7. In [155]: s
  8. Out[155]:
  9. 0 0.321438
  10. 1 0.493496
  11. 2 0.139505
  12. 3 0.910103
  13. 4 0.194158
  14. dtype: float64
  15.  
  16. In [156]: s.apply(f)
  17. Out[156]:
  18. x x^2
  19. 0 0.321438 0.103323
  20. 1 0.493496 0.243538
  21. 2 0.139505 0.019462
  22. 3 0.910103 0.828287
  23. 4 0.194158 0.037697

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 inthe output as well as set the indices.

Other useful features

Automatic exclusion of “nuisance” columns

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

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

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

  1. In [158]: df.groupby('A').std()
  2. Out[158]:
  3. C D
  4. A
  5. bar 0.181231 1.366330
  6. foo 0.912265 0.884785

Note that df.groupby('A').colname.std(). is more efficient thandf.groupby('A').std().colname, so if the result of an aggregation functionis only interesting over one column (here colname), it may be filteredbefore applying the aggregation function.

Note

Any object column, also if it contains numerical values such as Decimalobjects, is considered as a “nuisance” columns. They are excluded fromaggregate functions automatically in groupby.

If you do wish to include decimal or object columns in an aggregation withother non-nuisance data types, you must do so explicitly.

  1. In [159]: from decimal import Decimal
  2.  
  3. In [160]: df_dec = pd.DataFrame(
  4. .....: {'id': [1, 2, 1, 2],
  5. .....: 'int_column': [1, 2, 3, 4],
  6. .....: 'dec_column': [Decimal('0.50'), Decimal('0.15'),
  7. .....: Decimal('0.25'), Decimal('0.40')]
  8. .....: }
  9. .....: )
  10. .....:
  11.  
  12. # Decimal columns can be sum'd explicitly by themselves...
  13. In [161]: df_dec.groupby(['id'])[['dec_column']].sum()
  14. Out[161]:
  15. dec_column
  16. id
  17. 1 0.75
  18. 2 0.55
  19.  
  20. # ...but cannot be combined with standard data types or they will be excluded
  21. In [162]: df_dec.groupby(['id'])[['int_column', 'dec_column']].sum()
  22. Out[162]:
  23. int_column
  24. id
  25. 1 4
  26. 2 6
  27.  
  28. # Use .agg function to aggregate over standard and "nuisance" data types
  29. # at the same time
  30. In [163]: df_dec.groupby(['id']).agg({'int_column': 'sum', 'dec_column': 'sum'})
  31. Out[163]:
  32. int_column dec_column
  33. id
  34. 1 4 0.75
  35. 2 6 0.55

Handling of (un)observed Categorical values

When using a Categorical grouper (as a single grouper, or as part of multiple groupers), the observed keywordcontrols whether to return a cartesian product of all possible groupers values (observed=False) or only thosethat are observed groupers (observed=True).

Show all values:

  1. In [164]: pd.Series([1, 1, 1]).groupby(pd.Categorical(['a', 'a', 'a'],
  2. .....: categories=['a', 'b']),
  3. .....: observed=False).count()
  4. .....:
  5. Out[164]:
  6. a 3
  7. b 0
  8. dtype: int64

Show only the observed values:

  1. In [165]: pd.Series([1, 1, 1]).groupby(pd.Categorical(['a', 'a', 'a'],
  2. .....: categories=['a', 'b']),
  3. .....: observed=True).count()
  4. .....:
  5. Out[165]:
  6. a 3
  7. dtype: int64

The returned dtype of the grouped will always include all of the categories that were grouped.

  1. In [166]: s = pd.Series([1, 1, 1]).groupby(pd.Categorical(['a', 'a', 'a'],
  2. .....: categories=['a', 'b']),
  3. .....: observed=False).count()
  4. .....:
  5.  
  6. In [167]: s.index.dtype
  7. Out[167]: CategoricalDtype(categories=['a', 'b'], ordered=False)

NA and NaT group handling

If there are any NaN or NaT values in the grouping key, these will beautomatically excluded. In other words, there will never be an “NA group” or“NaT group”. This was not the case in older versions of pandas, but users weregenerally discarding the NA group anyway (and supporting it was animplementation headache).

Grouping with ordered factors

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

  1. In [168]: data = pd.Series(np.random.randn(100))
  2.  
  3. In [169]: factor = pd.qcut(data, [0, .25, .5, .75, 1.])
  4.  
  5. In [170]: data.groupby(factor).mean()
  6. Out[170]:
  7. (-2.645, -0.523] -1.362896
  8. (-0.523, 0.0296] -0.260266
  9. (0.0296, 0.654] 0.361802
  10. (0.654, 2.21] 1.073801
  11. dtype: float64

Grouping with a grouper specification

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

  1. In [171]: import datetime
  2.  
  3. In [172]: df = pd.DataFrame({'Branch': 'A A A A A A A B'.split(),
  4. .....: 'Buyer': 'Carl Mark Carl Carl Joe Joe Joe Carl'.split(),
  5. .....: 'Quantity': [1, 3, 5, 1, 8, 1, 9, 3],
  6. .....: 'Date': [
  7. .....: datetime.datetime(2013, 1, 1, 13, 0),
  8. .....: datetime.datetime(2013, 1, 1, 13, 5),
  9. .....: datetime.datetime(2013, 10, 1, 20, 0),
  10. .....: datetime.datetime(2013, 10, 2, 10, 0),
  11. .....: datetime.datetime(2013, 10, 1, 20, 0),
  12. .....: datetime.datetime(2013, 10, 2, 10, 0),
  13. .....: datetime.datetime(2013, 12, 2, 12, 0),
  14. .....: datetime.datetime(2013, 12, 2, 14, 0)]
  15. .....: })
  16. .....:
  17.  
  18. In [173]: df
  19. Out[173]:
  20. Branch Buyer Quantity Date
  21. 0 A Carl 1 2013-01-01 13:00:00
  22. 1 A Mark 3 2013-01-01 13:05:00
  23. 2 A Carl 5 2013-10-01 20:00:00
  24. 3 A Carl 1 2013-10-02 10:00:00
  25. 4 A Joe 8 2013-10-01 20:00:00
  26. 5 A Joe 1 2013-10-02 10:00:00
  27. 6 A Joe 9 2013-12-02 12:00:00
  28. 7 B Carl 3 2013-12-02 14:00:00

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

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

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

  1. In [175]: df = df.set_index('Date')
  2.  
  3. In [176]: df['Date'] = df.index + pd.offsets.MonthEnd(2)
  4.  
  5. In [177]: df.groupby([pd.Grouper(freq='6M', key='Date'), 'Buyer']).sum()
  6. Out[177]:
  7. Quantity
  8. Date Buyer
  9. 2013-02-28 Carl 1
  10. Mark 3
  11. 2014-02-28 Carl 9
  12. Joe 18
  13.  
  14. In [178]: df.groupby([pd.Grouper(freq='6M', level='Date'), 'Buyer']).sum()
  15. Out[178]:
  16. Quantity
  17. Date Buyer
  18. 2013-01-31 Carl 1
  19. Mark 3
  20. 2014-01-31 Carl 9
  21. 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:

  1. In [179]: df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])
  2.  
  3. In [180]: df
  4. Out[180]:
  5. A B
  6. 0 1 2
  7. 1 1 4
  8. 2 5 6
  9.  
  10. In [181]: g = df.groupby('A')
  11.  
  12. In [182]: g.head(1)
  13. Out[182]:
  14. A B
  15. 0 1 2
  16. 2 5 6
  17.  
  18. In [183]: g.tail(1)
  19. Out[183]:
  20. A B
  21. 1 1 4
  22. 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, usenth(). This is a reduction method, andwill return a single row (or no row) per group if you pass an int for n:

  1. In [184]: df = pd.DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
  2.  
  3. In [185]: g = df.groupby('A')
  4.  
  5. In [186]: g.nth(0)
  6. Out[186]:
  7. B
  8. A
  9. 1 NaN
  10. 5 6.0
  11.  
  12. In [187]: g.nth(-1)
  13. Out[187]:
  14. B
  15. A
  16. 1 4.0
  17. 5 6.0
  18.  
  19. In [188]: g.nth(1)
  20. Out[188]:
  21. B
  22. A
  23. 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:

  1. # nth(0) is the same as g.first()
  2. In [189]: g.nth(0, dropna='any')
  3. Out[189]:
  4. B
  5. A
  6. 1 4.0
  7. 5 6.0
  8.  
  9. In [190]: g.first()
  10. Out[190]:
  11. B
  12. A
  13. 1 4.0
  14. 5 6.0
  15.  
  16. # nth(-1) is the same as g.last()
  17. In [191]: g.nth(-1, dropna='any') # NaNs denote group exhausted when using dropna
  18. Out[191]:
  19. B
  20. A
  21. 1 4.0
  22. 5 6.0
  23.  
  24. In [192]: g.last()
  25. Out[192]:
  26. B
  27. A
  28. 1 4.0
  29. 5 6.0
  30.  
  31. In [193]: g.B.nth(0, dropna='all')
  32. Out[193]:
  33. A
  34. 1 4.0
  35. 5 6.0
  36. Name: B, dtype: float64

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

  1. In [194]: df = pd.DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
  2.  
  3. In [195]: g = df.groupby('A', as_index=False)
  4.  
  5. In [196]: g.nth(0)
  6. Out[196]:
  7. A B
  8. 0 1 NaN
  9. 2 5 6.0
  10.  
  11. In [197]: g.nth(-1)
  12. Out[197]:
  13. A B
  14. 1 1 4.0
  15. 2 5 6.0

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

  1. In [198]: business_dates = pd.date_range(start='4/1/2014', end='6/30/2014', freq='B')
  2.  
  3. In [199]: df = pd.DataFrame(1, index=business_dates, columns=['a', 'b'])
  4.  
  5. # get the first, 4th, and last date index for each month
  6. In [200]: df.groupby([df.index.year, df.index.month]).nth([0, 3, -1])
  7. Out[200]:
  8. a b
  9. 2014 4 1 1
  10. 4 1 1
  11. 4 1 1
  12. 5 1 1
  13. 5 1 1
  14. 5 1 1
  15. 6 1 1
  16. 6 1 1
  17. 6 1 1

Enumerate group items

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

  1. In [201]: dfg = pd.DataFrame(list('aaabba'), columns=['A'])
  2.  
  3. In [202]: dfg
  4. Out[202]:
  5. A
  6. 0 a
  7. 1 a
  8. 2 a
  9. 3 b
  10. 4 b
  11. 5 a
  12.  
  13. In [203]: dfg.groupby('A').cumcount()
  14. Out[203]:
  15. 0 0
  16. 1 1
  17. 2 2
  18. 3 0
  19. 4 1
  20. 5 3
  21. dtype: int64
  22.  
  23. In [204]: dfg.groupby('A').cumcount(ascending=False)
  24. Out[204]:
  25. 0 3
  26. 1 2
  27. 2 1
  28. 3 1
  29. 4 0
  30. 5 0
  31. dtype: int64

Enumerate groups

New in version 0.20.2.

To see the ordering of the groups (as opposed to the order of rowswithin a group given by cumcount) you can usengroup().

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

  1. In [205]: dfg = pd.DataFrame(list('aaabba'), columns=['A'])
  2.  
  3. In [206]: dfg
  4. Out[206]:
  5. A
  6. 0 a
  7. 1 a
  8. 2 a
  9. 3 b
  10. 4 b
  11. 5 a
  12.  
  13. In [207]: dfg.groupby('A').ngroup()
  14. Out[207]:
  15. 0 0
  16. 1 0
  17. 2 0
  18. 3 1
  19. 4 1
  20. 5 0
  21. dtype: int64
  22.  
  23. In [208]: dfg.groupby('A').ngroup(ascending=False)
  24. Out[208]:
  25. 0 1
  26. 1 1
  27. 2 1
  28. 3 0
  29. 4 0
  30. 5 1
  31. dtype: int64

Plotting

Groupby also works with some plotting methods. For example, suppose wesuspect 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.

  1. In [209]: np.random.seed(1234)
  2.  
  3. In [210]: df = pd.DataFrame(np.random.randn(50, 2))
  4.  
  5. In [211]: df['g'] = np.random.choice(['A', 'B'], size=50)
  6.  
  7. In [212]: df.loc[df['g'] == 'B', 1] += 3

We can easily visualize this with a boxplot:

  1. In [213]: df.groupby('g').boxplot()
  2. Out[213]:
  3. A AxesSubplot(0.1,0.15;0.363636x0.75)
  4. B AxesSubplot(0.536364,0.15;0.363636x0.75)
  5. dtype: object

../_images/groupby_boxplot.pngThe result of calling boxplot is a dictionary whose keys are the valuesof our grouping column g (“A” and “B”). The values of the resulting dictionarycan 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 equivalentto df.boxplot(by="g"). See here foran explanation.

Piping function calls

New in version 0.21.0.

Similar to the functionality provided by DataFrame and Series, functionsthat take GroupBy objects can be chained together using a pipe method toallow 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 reuseGroupBy objects.

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

  1. In [214]: n = 1000
  2.  
  3. In [215]: df = pd.DataFrame({'Store': np.random.choice(['Store_1', 'Store_2'], n),
  4. .....: 'Product': np.random.choice(['Product_1',
  5. .....: 'Product_2'], n),
  6. .....: 'Revenue': (np.random.random(n) * 50 + 10).round(2),
  7. .....: 'Quantity': np.random.randint(1, 10, size=n)})
  8. .....:
  9.  
  10. In [216]: df.head(2)
  11. Out[216]:
  12. Store Product Revenue Quantity
  13. 0 Store_2 Product_1 26.12 1
  14. 1 Store_2 Product_1 28.86 1

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

  1. In [217]: (df.groupby(['Store', 'Product'])
  2. .....: .pipe(lambda grp: grp.Revenue.sum() / grp.Quantity.sum())
  3. .....: .unstack().round(2))
  4. .....:
  5. Out[217]:
  6. Product Product_1 Product_2
  7. Store
  8. Store_1 6.82 7.05
  9. Store_2 6.30 6.64

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

  1. In [218]: def mean(groupby):
  2. .....: return groupby.mean()
  3. .....:
  4.  
  5. In [219]: df.groupby(['Store', 'Product']).pipe(mean)
  6. Out[219]:
  7. Revenue Quantity
  8. Store Product
  9. Store_1 Product_1 34.622727 5.075758
  10. Product_2 35.482815 5.029630
  11. Store_2 Product_1 32.972837 5.237589
  12. Product_2 34.684360 5.224000

where mean takes a GroupBy object and finds the mean of the Revenue and Quantitycolumns respectively for each Store-Product combination. The mean function canbe any function that takes in a GroupBy object; the .pipe will pass the GroupByobject as a parameter into the function you specify.

Examples

Regrouping by factor

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

  1. In [220]: df = pd.DataFrame({'a': [1, 0, 0], 'b': [0, 1, 0],
  2. .....: 'c': [1, 0, 0], 'd': [2, 3, 4]})
  3. .....:
  4.  
  5. In [221]: df
  6. Out[221]:
  7. a b c d
  8. 0 1 0 1 2
  9. 1 0 1 0 3
  10. 2 0 0 0 4
  11.  
  12. In [222]: df.groupby(df.sum(), axis=1).sum()
  13. Out[222]:
  14. 1 9
  15. 0 2 2
  16. 1 1 3
  17. 2 0 4

Multi-column factorization

By using ngroup(), we can extractinformation about the groups in a way similar to factorize() (as describedfurther in the reshaping API) but which appliesnaturally to multiple columns of mixed type and differentsources. This can be useful as an intermediate categorical-like stepin processing, when the relationships between the group rows are moreimportant than their content, or as input to an algorithm which onlyaccepts the integer encoding. (For more information about support inpandas for full categorical data, see the Categoricalintroduction and theAPI documentation.)

  1. In [223]: dfg = pd.DataFrame({"A": [1, 1, 2, 3, 2], "B": list("aaaba")})
  2.  
  3. In [224]: dfg
  4. Out[224]:
  5. A B
  6. 0 1 a
  7. 1 1 a
  8. 2 2 a
  9. 3 3 b
  10. 4 2 a
  11.  
  12. In [225]: dfg.groupby(["A", "B"]).ngroup()
  13. Out[225]:
  14. 0 0
  15. 1 0
  16. 2 1
  17. 3 2
  18. 4 1
  19. dtype: int64
  20.  
  21. In [226]: dfg.groupby(["A", [0, 0, 0, 1, 1]]).ngroup()
  22. Out[226]:
  23. 0 0
  24. 1 0
  25. 2 1
  26. 3 3
  27. 4 2
  28. 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.

  1. In [227]: df = pd.DataFrame(np.random.randn(10, 2))
  2.  
  3. In [228]: df
  4. Out[228]:
  5. 0 1
  6. 0 -0.793893 0.321153
  7. 1 0.342250 1.618906
  8. 2 -0.975807 1.918201
  9. 3 -0.810847 -1.405919
  10. 4 -1.977759 0.461659
  11. 5 0.730057 -1.316938
  12. 6 -0.751328 0.528290
  13. 7 -0.257759 -1.081009
  14. 8 0.505895 -1.701948
  15. 9 -1.006349 0.020208
  16.  
  17. In [229]: df.index // 5
  18. Out[229]: Int64Index([0, 0, 0, 0, 0, 1, 1, 1, 1, 1], dtype='int64')
  19.  
  20. In [230]: df.groupby(df.index // 5).std()
  21. Out[230]:
  22. 0 1
  23. 0 0.823647 1.312912
  24. 1 0.760109 0.942941

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 especiallyuseful in conjunction with reshaping operations such as stacking in which thecolumn index name will be used as the name of the inserted column:

  1. In [231]: df = pd.DataFrame({'a': [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2],
  2. .....: 'b': [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
  3. .....: 'c': [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
  4. .....: 'd': [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]})
  5. .....:
  6.  
  7. In [232]: def compute_metrics(x):
  8. .....: result = {'b_sum': x['b'].sum(), 'c_mean': x['c'].mean()}
  9. .....: return pd.Series(result, name='metrics')
  10. .....:
  11.  
  12. In [233]: result = df.groupby('a').apply(compute_metrics)
  13.  
  14. In [234]: result
  15. Out[234]:
  16. metrics b_sum c_mean
  17. a
  18. 0 2.0 0.5
  19. 1 2.0 0.5
  20. 2 2.0 0.5
  21.  
  22. In [235]: result.stack()
  23. Out[235]:
  24. a metrics
  25. 0 b_sum 2.0
  26. c_mean 0.5
  27. 1 b_sum 2.0
  28. c_mean 0.5
  29. 2 b_sum 2.0
  30. c_mean 0.5
  31. dtype: float64