{"id":136,"date":"2013-03-31T23:44:53","date_gmt":"2013-04-01T04:44:53","guid":{"rendered":"http:\/\/homepages.uc.edu\/~yaozo\/wordpress\/?p=136"},"modified":"2013-03-31T23:44:53","modified_gmt":"2013-04-01T04:44:53","slug":"group-by-split-apply-combine","status":"publish","type":"post","link":"https:\/\/zhuoyao.net\/index.php\/2013\/03\/31\/group-by-split-apply-combine\/","title":{"rendered":"Group By: split-apply-combine"},"content":{"rendered":"<p>By \u201cgroup by\u201d we are referring to a process involving one or more of the following steps<\/p>\n<blockquote>\n<ul>\n<li><strong>Splitting<\/strong>\u00a0the data into groups based on some criteria<\/li>\n<li><strong>Applying<\/strong>\u00a0a function to each group independently<\/li>\n<li><strong>Combining<\/strong>\u00a0the results into a data structure<\/li>\n<\/ul>\n<\/blockquote>\n<p>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:<\/p>\n<blockquote>\n<ul>\n<li><strong>Aggregation<\/strong>: computing a summary statistic (or statistics) about each group. Some examples:<br \/>\n<blockquote>\n<ul>\n<li>Compute group sums or means<\/li>\n<li>Compute group sizes \/ counts<\/li>\n<\/ul>\n<\/blockquote>\n<\/li>\n<li><strong>Transformation<\/strong>: perform some group-specific computations and return a like-indexed. Some examples:<br \/>\n<blockquote>\n<ul>\n<li>Standardizing data (zscore) within group<\/li>\n<li>Filling NAs within groups with a value derived from each group<\/li>\n<\/ul>\n<\/blockquote>\n<\/li>\n<li>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\u2019t fit into either of the above two categories<\/li>\n<\/ul>\n<\/blockquote>\n<p>Since the set of object instance method 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\u00a0<tt>itertools<\/tt>), in which you can write code like:<\/p>\n<div>\n<div>\n<pre>SELECT Column1, Column2, mean(Column3), sum(Column4)\nFROM SomeTable\nGROUP BY Column1, Column2<\/pre>\n<\/div>\n<\/div>\n<p>We aim to make operations like this natural and easy to express using pandas. We\u2019ll address each area of GroupBy functionality then provide some non-trivial examples \/ use cases.<\/p>\n<p>See some\u00a0<a href=\"http:\/\/pandas.pydata.org\/pandas-docs\/dev\/cookbook.html#cookbook-grouping\"><em>cookbook examples<\/em><\/a>\u00a0for some advanced strategies<\/p>\n<div id=\"splitting-an-object-into-groups\">\n<h2>Splitting an object into groups<\/h2>\n<p>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:<\/p>\n<div>\n<div>\n<pre>&gt;&gt;&gt; grouped = obj.groupby(key)\n&gt;&gt;&gt; grouped = obj.groupby(key, axis=1)\n&gt;&gt;&gt; grouped = obj.groupby([key1, key2])<\/pre>\n<\/div>\n<\/div>\n<p>The mapping can be specified many different ways:<\/p>\n<blockquote>\n<ul>\n<li>A Python function, to be called on each of the axis labels<\/li>\n<li>A list or NumPy array of the same length as the selected axis<\/li>\n<li>A dict or Series, providing a\u00a0<tt>label\u00a0-&gt;\u00a0group\u00a0name<\/tt>\u00a0mapping<\/li>\n<li>For DataFrame objects, a string indicating a column to be used to group. Of course\u00a0<tt>df.groupby('A')<\/tt>\u00a0is just syntactic sugar for\u00a0<tt>df.groupby(df['A'])<\/tt>, but it makes life simpler<\/li>\n<li>A list of any of the above things<\/li>\n<\/ul>\n<\/blockquote>\n<p>Collectively we refer to the grouping objects as the\u00a0<strong>keys<\/strong>. For example, consider the following DataFrame:<\/p>\n<div>\n<div>\n<pre>In [690]: df = DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',\n   .....:                        'foo', 'bar', 'foo', 'foo'],\n   .....:                 'B' : ['one', 'one', 'two', 'three',\n   .....:                        'two', 'two', 'one', 'three'],\n   .....:                 'C' : randn(8), 'D' : randn(8)})\n   .....:\n\nIn [691]: df\nOut[691]: \n     A      B         C         D\n0  foo    one  0.469112 -0.861849\n1  bar    one -0.282863 -2.104569\n2  foo    two -1.509059 -0.494929\n3  bar  three -1.135632  1.071804\n4  foo    two  1.212112  0.721555\n5  bar    two -0.173215 -0.706771\n6  foo    one  0.119209 -1.039575\n7  foo  three -1.044236  0.271860<\/pre>\n<\/div>\n<\/div>\n<p>We could naturally group by either the\u00a0<tt>A<\/tt>\u00a0or\u00a0<tt>B<\/tt>\u00a0columns or both:<\/p>\n<div>\n<div>\n<pre>In [692]: grouped = df.groupby('A')\n\nIn [693]: grouped = df.groupby(['A', 'B'])<\/pre>\n<\/div>\n<\/div>\n<p>These will split the DataFrame on its index (rows). We could also split by the columns:<\/p>\n<div>\n<div>\n<pre>In [694]: def get_letter_type(letter):\n   .....:     if letter.lower() in 'aeiou':\n   .....:         return 'vowel'\n   .....:     else:\n   .....:         return 'consonant'\n   .....:\n\nIn [695]: grouped = df.groupby(get_letter_type, axis=1)<\/pre>\n<\/div>\n<\/div>\n<p>Starting with 0.8, pandas Index objects now supports 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:<\/p>\n<div>\n<div>\n<pre>In [696]: lst = [1, 2, 3, 1, 2, 3]\n\nIn [697]: s = Series([1, 2, 3, 10, 20, 30], lst)\n\nIn [698]: grouped = s.groupby(level=0)\n\nIn [699]: grouped.first()\nOut[699]: \n1    1\n2    2\n3    3\ndtype: int64\n\nIn [700]: grouped.last()\nOut[700]: \n1    10\n2    20\n3    30\ndtype: int64\n\nIn [701]: grouped.sum()\nOut[701]: \n1    11\n2    22\n3    33\ndtype: int64<\/pre>\n<\/div>\n<\/div>\n<p>Note that\u00a0<strong>no splitting occurs<\/strong>\u00a0until it\u2019s needed. Creating the GroupBy object only verifies that you\u2019ve passed a valid mapping.<\/p>\n<div>\n<p>Note<\/p>\n<p>Many kinds of complicated data manipulations can be expressed in terms of GroupBy operations (though can\u2019t be guaranteed to be the most efficient). You can get quite creative with the label mapping functions.<\/p>\n<\/div>\n<div id=\"groupby-object-attributes\">\n<h3>GroupBy object attributes<\/h3>\n<p>The\u00a0<tt>groups<\/tt>\u00a0attribute 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:<\/p>\n<div>\n<div>\n<pre>In [702]: df.groupby('A').groups\nOut[702]: {'bar': [1, 3, 5], 'foo': [0, 2, 4, 6, 7]}\n\nIn [703]: df.groupby(get_letter_type, axis=1).groups\nOut[703]: {'consonant': ['B', 'C', 'D'], 'vowel': ['A']}<\/pre>\n<\/div>\n<\/div>\n<p>Calling the standard Python\u00a0<tt>len<\/tt>\u00a0function on the GroupBy object just returns the length of the\u00a0<tt>groups<\/tt>\u00a0dict, so it is largely just a convenience:<\/p>\n<div>\n<div>\n<pre>In [704]: grouped = df.groupby(['A', 'B'])\n\nIn [705]: grouped.groups\nOut[705]: \n{('bar', 'one'): [1],\n ('bar', 'three'): [3],\n ('bar', 'two'): [5],\n ('foo', 'one'): [0, 6],\n ('foo', 'three'): [7],\n ('foo', 'two'): [2, 4]}\n\nIn [706]: len(grouped)\nOut[706]: 6<\/pre>\n<\/div>\n<\/div>\n<p>By default the group keys are sorted during the groupby operation. You may however pass<tt>sort``=``False<\/tt>\u00a0for potential speedups:<\/p>\n<div>\n<div>\n<pre>In [707]: df2 = DataFrame({'X' : ['B', 'B', 'A', 'A'], 'Y' : [1, 2, 3, 4]})\n\nIn [708]: df2.groupby(['X'], sort=True).sum()\nOut[708]: \n   Y\nX   \nA  7\nB  3\n\nIn [709]: df2.groupby(['X'], sort=False).sum()\nOut[709]: \n   Y\nX   \nB  3\nA  7<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"groupby-with-multiindex\">\n<h3>GroupBy with MultiIndex<\/h3>\n<p>With\u00a0<a href=\"http:\/\/pandas.pydata.org\/pandas-docs\/dev\/indexing.html#indexing-hierarchical\"><em>hierarchically-indexed data<\/em><\/a>, it\u2019s quite natural to group by one of the levels of the hierarchy.<\/p>\n<div>\n<div>\n<pre>In [710]: s\nOut[710]: \nfirst  second\nbar    one      -0.424972\n       two       0.567020\nbaz    one       0.276232\n       two      -1.087401\nfoo    one      -0.673690\n       two       0.113648\nqux    one      -1.478427\n       two       0.524988\ndtype: float64\n\nIn [711]: grouped = s.groupby(level=0)\n\nIn [712]: grouped.sum()\nOut[712]: \nfirst\nbar      0.142048\nbaz     -0.811169\nfoo     -0.560041\nqux     -0.953439\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<p>If the MultiIndex has names specified, these can be passed instead of the level number:<\/p>\n<div>\n<div>\n<pre>In [713]: s.groupby(level='second').sum()\nOut[713]: \nsecond\none      -2.300857\ntwo       0.118256\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<p>The aggregation functions such as\u00a0<tt>sum<\/tt>\u00a0will take the level parameter directly. Additionally, the resulting index will be named according to the chosen level:<\/p>\n<div>\n<div>\n<pre>In [714]: s.sum(level='second')\nOut[714]: \nsecond\none      -2.300857\ntwo       0.118256\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<p>Also as of v0.6, grouping with multiple levels is supported.<\/p>\n<div>\n<div>\n<pre>In [715]: s\nOut[715]: \nfirst  second  third\nbar    doo     one      0.404705\n               two      0.577046\nbaz    bee     one     -1.715002\n               two     -1.039268\nfoo    bop     one     -0.370647\n               two     -1.157892\nqux    bop     one     -1.344312\n               two      0.844885\ndtype: float64\n\nIn [716]: s.groupby(level=['first','second']).sum()\nOut[716]: \nfirst  second\nbar    doo       0.981751\nbaz    bee      -2.754270\nfoo    bop      -1.528539\nqux    bop      -0.499427\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<p>More on the\u00a0<tt>sum<\/tt>\u00a0function and aggregation later.<\/p>\n<\/div>\n<div id=\"dataframe-column-selection-in-groupby\">\n<h3>DataFrame column selection in GroupBy<\/h3>\n<p>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\u00a0<tt>[]<\/tt>\u00a0similar to getting a column from a DataFrame, you can do:<\/p>\n<div>\n<div>\n<pre>In [717]: grouped = df.groupby(['A'])\n\nIn [718]: grouped_C = grouped['C']\n\nIn [719]: grouped_D = grouped['D']<\/pre>\n<\/div>\n<\/div>\n<p>This is mainly syntactic sugar for the alternative and much more verbose:<\/p>\n<div>\n<div>\n<pre>In [720]: df['C'].groupby(df['A'])\nOut[720]: &lt;pandas.core.groupby.SeriesGroupBy at 0xb60fe10&gt;<\/pre>\n<\/div>\n<\/div>\n<p>Additionally this method avoids recomputing the internal grouping information derived from the passed key.<\/p>\n<\/div>\n<\/div>\n<div id=\"iterating-through-groups\">\n<h2>Iterating through groups<\/h2>\n<p>With the GroupBy object in hand, iterating through the grouped data is very natural and functions similarly to\u00a0<tt>itertools.groupby<\/tt>:<\/p>\n<div>\n<div>\n<pre>In [721]: grouped = df.groupby('A')\n\nIn [722]: for name, group in grouped:\n   .....:        print name\n   .....:        print group\n   .....:\nbar\n     A      B         C         D\n1  bar    one -0.282863 -2.104569\n3  bar  three -1.135632  1.071804\n5  bar    two -0.173215 -0.706771\nfoo\n     A      B         C         D\n0  foo    one  0.469112 -0.861849\n2  foo    two -1.509059 -0.494929\n4  foo    two  1.212112  0.721555\n6  foo    one  0.119209 -1.039575\n7  foo  three -1.044236  0.271860<\/pre>\n<\/div>\n<\/div>\n<p>In the case of grouping by multiple keys, the group name will be a tuple:<\/p>\n<div>\n<div>\n<pre>In [723]: for name, group in df.groupby(['A', 'B']):\n   .....:        print name\n   .....:        print group\n   .....:\n('bar', 'one')\n     A    B         C         D\n1  bar  one -0.282863 -2.104569\n('bar', 'three')\n     A      B         C         D\n3  bar  three -1.135632  1.071804\n('bar', 'two')\n     A    B         C         D\n5  bar  two -0.173215 -0.706771\n('foo', 'one')\n     A    B         C         D\n0  foo  one  0.469112 -0.861849\n6  foo  one  0.119209 -1.039575\n('foo', 'three')\n     A      B         C        D\n7  foo  three -1.044236  0.27186\n('foo', 'two')\n     A    B         C         D\n2  foo  two -1.509059 -0.494929\n4  foo  two  1.212112  0.721555<\/pre>\n<\/div>\n<\/div>\n<p>It\u2019s standard Python-fu but remember you can unpack the tuple in the for loop statement if you wish:\u00a0<tt>for\u00a0(k1,\u00a0k2),\u00a0group\u00a0in\u00a0grouped:<\/tt>.<\/p>\n<\/div>\n<div id=\"aggregation\">\n<h2>Aggregation<\/h2>\n<p>Once the GroupBy object has been created, several methods are available to perform a computation on the grouped data. An obvious one is aggregation via the\u00a0<tt>aggregate<\/tt>\u00a0or equivalently\u00a0<tt>agg<\/tt>\u00a0method:<\/p>\n<div>\n<div>\n<pre>In [724]: grouped = df.groupby('A')\n\nIn [725]: grouped.aggregate(np.sum)\nOut[725]: \n            C         D\nA                      \nbar -1.591710 -1.739537\nfoo -0.752861 -1.402938\n\nIn [726]: grouped = df.groupby(['A', 'B'])\n\nIn [727]: grouped.aggregate(np.sum)\nOut[727]: \n                  C         D\nA   B                        \nbar one   -0.282863 -2.104569\n    three -1.135632  1.071804\n    two   -0.173215 -0.706771\nfoo one    0.588321 -1.901424\n    three -1.044236  0.271860\n    two   -0.296946  0.226626<\/pre>\n<\/div>\n<\/div>\n<p>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\u00a0<a href=\"http:\/\/pandas.pydata.org\/pandas-docs\/dev\/indexing.html#indexing-hierarchical\"><em>MultiIndex<\/em><\/a>\u00a0by default, though this can be changed by using the\u00a0<tt>as_index<\/tt>\u00a0option:<\/p>\n<div>\n<div>\n<pre>In [728]: grouped = df.groupby(['A', 'B'], as_index=False)\n\nIn [729]: grouped.aggregate(np.sum)\nOut[729]: \n     A      B         C         D\n0  bar    one -0.282863 -2.104569\n1  bar  three -1.135632  1.071804\n2  bar    two -0.173215 -0.706771\n3  foo    one  0.588321 -1.901424\n4  foo  three -1.044236  0.271860\n5  foo    two -0.296946  0.226626\n\nIn [730]: df.groupby('A', as_index=False).sum()\nOut[730]: \n     A         C         D\n0  bar -1.591710 -1.739537\n1  foo -0.752861 -1.402938<\/pre>\n<\/div>\n<\/div>\n<p>Note that you could use the\u00a0<tt>reset_index<\/tt>\u00a0DataFrame function to achieve the same result as the column names are stored in the resulting\u00a0<tt>MultiIndex<\/tt>:<\/p>\n<div>\n<div>\n<pre>In [731]: df.groupby(['A', 'B']).sum().reset_index()\nOut[731]: \n     A      B         C         D\n0  bar    one -0.282863 -2.104569\n1  bar  three -1.135632  1.071804\n2  bar    two -0.173215 -0.706771\n3  foo    one  0.588321 -1.901424\n4  foo  three -1.044236  0.271860\n5  foo    two -0.296946  0.226626<\/pre>\n<\/div>\n<\/div>\n<p>Another simple aggregation example is to compute the size of each group. This is included in GroupBy as the\u00a0<tt>size<\/tt>\u00a0method. It returns a Series whose index are the group names and whose values are the sizes of each group.<\/p>\n<div>\n<div>\n<pre>In [732]: grouped.size()\nOut[732]: \nA    B    \nbar  one      1\n     three    1\n     two      1\nfoo  one      2\n     three    1\n     two      2\ndtype: int64<\/pre>\n<\/div>\n<\/div>\n<div id=\"applying-multiple-functions-at-once\">\n<h3>Applying multiple functions at once<\/h3>\n<p>With grouped Series you can also pass a list or dict of functions to do aggregation with, outputting a DataFrame:<\/p>\n<div>\n<div>\n<pre>In [733]: grouped = df.groupby('A')\n\nIn [734]: grouped['C'].agg([np.sum, np.mean, np.std])\nOut[734]: \n          sum      mean       std\nA                                \nbar -1.591710 -0.530570  0.526860\nfoo -0.752861 -0.150572  1.113308<\/pre>\n<\/div>\n<\/div>\n<p>If a dict is passed, the keys will be used to name the columns. Otherwise the function\u2019s name (stored in the function object) will be used.<\/p>\n<div>\n<div>\n<pre>In [735]: grouped['D'].agg({'result1' : np.sum,\n   .....:                   'result2' : np.mean})\n   .....:\nOut[735]: \n      result2   result1\nA                      \nbar -0.579846 -1.739537\nfoo -0.280588 -1.402938<\/pre>\n<\/div>\n<\/div>\n<p>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:<\/p>\n<div>\n<div>\n<pre>In [736]: grouped.agg([np.sum, np.mean, np.std])\nOut[736]: \n            C                             D                    \n          sum      mean       std       sum      mean       std\nA                                                              \nbar -1.591710 -0.530570  0.526860 -1.739537 -0.579846  1.591986\nfoo -0.752861 -0.150572  1.113308 -1.402938 -0.280588  0.753219<\/pre>\n<\/div>\n<\/div>\n<p>Passing a dict of functions has different behavior by default, see the next section.<\/p>\n<\/div>\n<div id=\"applying-different-functions-to-dataframe-columns\">\n<h3>Applying different functions to DataFrame columns<\/h3>\n<p>By passing a dict to\u00a0<tt>aggregate<\/tt>\u00a0you can apply a different aggregation to the columns of a DataFrame:<\/p>\n<div>\n<div>\n<pre>In [737]: grouped.agg({'C' : np.sum,\n   .....:              'D' : lambda x: np.std(x, ddof=1)})\n   .....:\nOut[737]: \n            C         D\nA                      \nbar -1.591710  1.591986\nfoo -0.752861  0.753219<\/pre>\n<\/div>\n<\/div>\n<p>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\u00a0<a href=\"http:\/\/pandas.pydata.org\/pandas-docs\/dev\/groupby.html#groupby-dispatch\"><em>dispatching<\/em><\/a>:<\/p>\n<div>\n<div>\n<pre>In [738]: grouped.agg({'C' : 'sum', 'D' : 'std'})\nOut[738]: \n            C         D\nA                      \nbar -1.591710  1.591986\nfoo -0.752861  0.753219<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"cython-optimized-aggregation-functions\">\n<h3>Cython-optimized aggregation functions<\/h3>\n<p>Some common aggregations, currently only\u00a0<tt>sum<\/tt>,\u00a0<tt>mean<\/tt>, and\u00a0<tt>std<\/tt>, have optimized Cython implementations:<\/p>\n<div>\n<div>\n<pre>In [739]: df.groupby('A').sum()\nOut[739]: \n            C         D\nA                      \nbar -1.591710 -1.739537\nfoo -0.752861 -1.402938\n\nIn [740]: df.groupby(['A', 'B']).mean()\nOut[740]: \n                  C         D\nA   B                        \nbar one   -0.282863 -2.104569\n    three -1.135632  1.071804\n    two   -0.173215 -0.706771\nfoo one    0.294161 -0.950712\n    three -1.044236  0.271860\n    two   -0.148473  0.113313<\/pre>\n<\/div>\n<\/div>\n<p>Of course\u00a0<tt>sum<\/tt>\u00a0and\u00a0<tt>mean<\/tt>\u00a0are implemented on pandas objects, so the above code would work even without the special versions via dispatching (see below).<\/p>\n<\/div>\n<\/div>\n<div id=\"transformation\">\n<h2>Transformation<\/h2>\n<p>The\u00a0<tt>transform<\/tt>\u00a0method returns an object that is indexed the same (same size) as the one being grouped. Thus, the passed transform function should return a result that is the same size as the group chunk. For example, suppose we wished to standardize the data within each group:<\/p>\n<div>\n<div>\n<pre>In [741]: index = date_range('10\/1\/1999', periods=1100)\n\nIn [742]: ts = Series(np.random.normal(0.5, 2, 1100), index)\n\nIn [743]: ts = rolling_mean(ts, 100, 100).dropna()\n\nIn [744]: ts.head()\nOut[744]: \n2000-01-08    0.536925\n2000-01-09    0.494448\n2000-01-10    0.496114\n2000-01-11    0.443475\n2000-01-12    0.474744\nFreq: D, dtype: float64\n\nIn [745]: ts.tail()\nOut[745]: \n2002-09-30    0.978859\n2002-10-01    0.994704\n2002-10-02    0.953789\n2002-10-03    0.932345\n2002-10-04    0.915581\nFreq: D, dtype: float64\n\nIn [746]: key = lambda x: x.year\n\nIn [747]: zscore = lambda x: (x - x.mean()) \/ x.std()\n\nIn [748]: transformed = ts.groupby(key).transform(zscore)<\/pre>\n<\/div>\n<\/div>\n<p>We would expect the result to now have mean 0 and standard deviation 1 within each group, which we can easily check:<\/p>\n<div>\n<div>\n<pre># Original Data\nIn [749]: grouped = ts.groupby(key)\n\nIn [750]: grouped.mean()\nOut[750]: \n2000    0.416344\n2001    0.416987\n2002    0.599380\ndtype: float64\n\nIn [751]: grouped.std()\nOut[751]: \n2000    0.174755\n2001    0.309640\n2002    0.266172\ndtype: float64\n\n# Transformed Data\nIn [752]: grouped_trans = transformed.groupby(key)\n\nIn [753]: grouped_trans.mean()\nOut[753]: \n2000   -5.108881e-16\n2001   -3.808217e-16\n2002   -8.577174e-17\ndtype: float64\n\nIn [754]: grouped_trans.std()\nOut[754]: \n2000    1\n2001    1\n2002    1\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<p>We can also visually compare the original and transformed data sets.<\/p>\n<div>\n<div>\n<pre>In [755]: compare = DataFrame({'Original': ts, 'Transformed': transformed})\n\nIn [756]: compare.plot()\nOut[756]: &lt;matplotlib.axes.AxesSubplot at 0xbb5bc50&gt;<\/pre>\n<\/div>\n<\/div>\n<p><img decoding=\"async\" alt=\"_images\/groupby_transform_plot.png\" src=\"http:\/\/pandas.pydata.org\/pandas-docs\/dev\/_images\/groupby_transform_plot.png\" \/>Another common data transform is to replace missing data with the group mean.<\/p>\n<div>\n<div>\n<pre>In [757]: data_df\nOut[757]: \n&lt;class 'pandas.core.frame.DataFrame'&gt;\nInt64Index: 1000 entries, 0 to 999\nData columns (total 3 columns):\nA    908  non-null values\nB    953  non-null values\nC    820  non-null values\ndtypes: float64(3)\n\nIn [758]: countries = np.array(['US', 'UK', 'GR', 'JP'])\n\nIn [759]: key = countries[np.random.randint(0, 4, 1000)]\n\nIn [760]: grouped = data_df.groupby(key)\n\n# Non-NA count in each group\nIn [761]: grouped.count()\nOut[761]: \n      A    B    C\nGR  219  223  194\nJP  238  250  211\nUK  228  239  213\nUS  223  241  202\n\nIn [762]: f = lambda x: x.fillna(x.mean())\n\nIn [763]: transformed = grouped.transform(f)<\/pre>\n<\/div>\n<\/div>\n<p>We can verify that the group means have not changed in the transformed data and that the transformed data contains no NAs.<\/p>\n<div>\n<div>\n<pre>In [764]: grouped_trans = transformed.groupby(key)\n\nIn [765]: grouped.mean() # original group means\nOut[765]: \n           A         B         C\nGR  0.093655 -0.004978 -0.049883\nJP -0.067605  0.025828  0.006752\nUK -0.054246  0.031742  0.068974\nUS  0.084334 -0.013433  0.056589\n\nIn [766]: grouped_trans.mean() # transformation did not change group means\nOut[766]: \n           A         B         C\nGR  0.093655 -0.004978 -0.049883\nJP -0.067605  0.025828  0.006752\nUK -0.054246  0.031742  0.068974\nUS  0.084334 -0.013433  0.056589\n\nIn [767]: grouped.count() # original has some missing data points\nOut[767]: \n      A    B    C\nGR  219  223  194\nJP  238  250  211\nUK  228  239  213\nUS  223  241  202\n\nIn [768]: grouped_trans.count() # counts after transformation\nOut[768]: \n      A    B    C\nGR  234  234  234\nJP  264  264  264\nUK  251  251  251\nUS  251  251  251\n\nIn [769]: grouped_trans.size() # Verify non-NA count equals group size\nOut[769]: \nGR    234\nJP    264\nUK    251\nUS    251\ndtype: int64<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"dispatching-to-instance-methods\">\n<h2>Dispatching to instance methods<\/h2>\n<p>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:<\/p>\n<div>\n<div>\n<pre>In [770]: grouped = df.groupby('A')\n\nIn [771]: grouped.agg(lambda x: x.std())\nOut[771]: \n      B         C         D\nA                          \nbar NaN  0.526860  1.591986\nfoo NaN  1.113308  0.753219<\/pre>\n<\/div>\n<\/div>\n<p>But, it\u2019s 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 \u201cdispatch\u201d method calls to the groups:<\/p>\n<div>\n<div>\n<pre>In [772]: grouped.std()\nOut[772]: \n            C         D\nA                      \nbar  0.526860  1.591986\nfoo  1.113308  0.753219<\/pre>\n<\/div>\n<\/div>\n<p>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\u00a0<tt>std<\/tt>\u00a0function). The results are then combined together much in the style of\u00a0<tt>agg<\/tt>\u00a0and\u00a0<tt>transform<\/tt>\u00a0(it actually uses\u00a0<tt>apply<\/tt>\u00a0to infer the gluing, documented next). This enables some operations to be carried out rather succinctly:<\/p>\n<div>\n<div>\n<pre>In [773]: tsdf = DataFrame(randn(1000, 3),\n   .....:                  index=date_range('1\/1\/2000', periods=1000),\n   .....:                  columns=['A', 'B', 'C'])\n   .....:\n\nIn [774]: tsdf.ix[::2] = np.nan\n\nIn [775]: grouped = tsdf.groupby(lambda x: x.year)\n\nIn [776]: grouped.fillna(method='pad')\nOut[776]: \n&lt;class 'pandas.core.frame.DataFrame'&gt;\nDatetimeIndex: 1000 entries, 2000-01-01 00:00:00 to 2002-09-26 00:00:00\nFreq: D\nData columns (total 3 columns):\nA    998  non-null values\nB    998  non-null values\nC    998  non-null values\ndtypes: float64(3)<\/pre>\n<\/div>\n<\/div>\n<p>In this example, we chopped the collection of time series into yearly chunks then independently called\u00a0<a href=\"http:\/\/pandas.pydata.org\/pandas-docs\/dev\/missing_data.html#missing-data-fillna\"><em>fillna<\/em><\/a>\u00a0on the groups.<\/p>\n<\/div>\n<div id=\"flexible-apply\">\n<h2>Flexible\u00a0<tt>apply<\/tt><\/h2>\n<p>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\u00a0<tt>apply<\/tt>\u00a0function, which can be substituted for both\u00a0<tt>aggregate<\/tt>\u00a0and\u00a0<tt>transform<\/tt>\u00a0in many standard use cases. However,\u00a0<tt>apply<\/tt>\u00a0can handle some exceptional use cases, for example:<\/p>\n<div>\n<div>\n<pre>In [777]: df\nOut[777]: \n     A      B         C         D\n0  foo    one  0.469112 -0.861849\n1  bar    one -0.282863 -2.104569\n2  foo    two -1.509059 -0.494929\n3  bar  three -1.135632  1.071804\n4  foo    two  1.212112  0.721555\n5  bar    two -0.173215 -0.706771\n6  foo    one  0.119209 -1.039575\n7  foo  three -1.044236  0.271860\n\nIn [778]: grouped = df.groupby('A')\n\n# could also just call .describe()\nIn [779]: grouped['C'].apply(lambda x: x.describe())\nOut[779]: \nA         \nbar  count    3.000000\n     mean    -0.530570\n     std      0.526860\n     min     -1.135632\n     25%     -0.709248\n     50%     -0.282863\n     75%     -0.228039\n     max     -0.173215\nfoo  count    5.000000\n     mean    -0.150572\n     std      1.113308\n     min     -1.509059\n     25%     -1.044236\n     50%      0.119209\n     75%      0.469112\n     max      1.212112\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<p>The dimension of the returned result can also change:<\/p>\n<div>\n<div>\n<pre>In [780]: grouped = df.groupby('A')['C']\n\nIn [781]: def f(group):\n   .....:     return DataFrame({'original' : group,\n   .....:                       'demeaned' : group - group.mean()})\n   .....:\n\nIn [782]: grouped.apply(f)\nOut[782]: \n   demeaned  original\n0  0.619685  0.469112\n1  0.247707 -0.282863\n2 -1.358486 -1.509059\n3 -0.605062 -1.135632\n4  1.362684  1.212112\n5  0.357355 -0.173215\n6  0.269781  0.119209\n7 -0.893664 -1.044236<\/pre>\n<\/div>\n<\/div>\n<p><tt>apply<\/tt>\u00a0on 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<\/p>\n<div>\n<div>\n<pre>In [783]: def f(x):\n   .....:        return Series([ x, x**2 ], index = ['x', 'x^s'])\n   .....:\n\nIn [784]: s = Series(np.random.rand(5))\n\nIn [785]: s\nOut[785]: \n0    0.785887\n1    0.498525\n2    0.933703\n3    0.154106\n4    0.271779\ndtype: float64\n\nIn [786]: s.apply(f)\nOut[786]: \n          x       x^s\n0  0.785887  0.617619\n1  0.498525  0.248528\n2  0.933703  0.871801\n3  0.154106  0.023749\n4  0.271779  0.073864<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"other-useful-features\">\n<h2>Other useful features<\/h2>\n<div id=\"automatic-exclusion-of-nuisance-columns\">\n<h3>Automatic exclusion of \u201cnuisance\u201d columns<\/h3>\n<p>Again consider the example DataFrame we\u2019ve been looking at:<\/p>\n<div>\n<div>\n<pre>In [787]: df\nOut[787]: \n     A      B         C         D\n0  foo    one  0.469112 -0.861849\n1  bar    one -0.282863 -2.104569\n2  foo    two -1.509059 -0.494929\n3  bar  three -1.135632  1.071804\n4  foo    two  1.212112  0.721555\n5  bar    two -0.173215 -0.706771\n6  foo    one  0.119209 -1.039575\n7  foo  three -1.044236  0.271860<\/pre>\n<\/div>\n<\/div>\n<p>Supposed we wished to compute the standard deviation grouped by the\u00a0<tt>A<\/tt>\u00a0column. There is a slight problem, namely that we don\u2019t care about the data in column\u00a0<tt>B<\/tt>. We refer to this as a \u201cnuisance\u201d column. If the passed aggregation function can\u2019t be applied to some columns, the troublesome columns will be (silently) dropped. Thus, this does not pose any problems:<\/p>\n<div>\n<div>\n<pre>In [788]: df.groupby('A').std()\nOut[788]: \n            C         D\nA                      \nbar  0.526860  1.591986\nfoo  1.113308  0.753219<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"na-group-handling\">\n<h3>NA group handling<\/h3>\n<p>If there are any NaN values in the grouping key, these will be automatically excluded. So there will never be an \u201cNA group\u201d. 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).<\/p>\n<\/div>\n<div id=\"grouping-with-ordered-factors\">\n<h3>Grouping with ordered factors<\/h3>\n<p>Categorical variables represented as instance of pandas\u2019s\u00a0<tt>Factor<\/tt>\u00a0class can be used as group keys. If so, the order of the levels will be preserved:<\/p>\n<div>\n<div>\n<pre>In [789]: data = Series(np.random.randn(100))\n\nIn [790]: factor = qcut(data, [0, .25, .5, .75, 1.])\n\nIn [791]: data.groupby(factor).mean()\nOut[791]: \n[-3.469, -0.737]   -1.269581\n(-0.737, 0.214]    -0.216269\n(0.214, 1.0572]     0.680402\n(1.0572, 3.0762]    1.629338\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>By \u201cgroup by\u201d we are referring to a process involving one or more of the following steps Splitting\u00a0the data into groups based on some criteria&hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[19],"tags":[],"class_list":["post-136","post","type-post","status-publish","format-standard","hentry","category-python"],"_links":{"self":[{"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/posts\/136","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/comments?post=136"}],"version-history":[{"count":0,"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/posts\/136\/revisions"}],"wp:attachment":[{"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/media?parent=136"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/categories?post=136"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/tags?post=136"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}