By “group by” we are referring to a process involving one or more of the following
steps:
Splitting the data into groups based on some criteria.
Applying a function to each group independently.
Combining the results into a data structure.
Out of these, the split step is the most straightforward. In the apply step, we
might wish to do one of the following:
Aggregation: compute a summary statistic (or statistics) for each
group. Some examples:
Compute group sums or means.
Compute group sizes / counts.
Transformation: perform some group-specific computations and return a
like-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 computation
that evaluates to True or False. Some examples:
Discard data that belong to groups with only a few members.
Filter out data based on the group sum or mean.
Many of these operations are defined on GroupBy objects. These operations are similar
to those of the aggregating API,
window API, and resample API.
It is possible that a given operation does not fall into one of these categories or
is some combination of them. In such a case, it may be possible to compute the
operation using GroupBy’s apply method. This method will examine the results of the
apply step and try to sensibly combine them into a single result if it doesn’t fit into either
of the above three categories.
The name GroupBy should be quite familiar to those who have used
a SQL-based tool (or itertools), in which you can write code like:
We aim to make operations like this natural and easy to express using
pandas. We’ll address each area of GroupBy functionality, then provide some
non-trivial examples / use cases.
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 may do the following:
A Python function, to be called on each of the index labels.
A list or NumPy array of the same length as the index.
A dict or Series, providing a label->groupname mapping.
For DataFrame objects, a string indicating either a column name or
an index level name to be used to group.
A list of any of the above things.
Collectively we refer to the grouping objects as the keys. For example,
consider the following DataFrame:
In [5]: df=pd.DataFrame( ...: { ...: "A":["foo","bar","foo","bar","foo","bar","foo","foo"], ...: "B":["one","one",
On a DataFrame, we obtain a GroupBy object by calling groupby().
This method returns a pandas.api.typing.DataFrameGroupBy instance.
We could naturally group by either the A or B columns, or both:
In [7]: grouped=df.groupby("A")In [8]: grouped=df.groupby("B")In [9]: grouped=df.groupby(["A","B"])
If we also have a MultiIndex on columns A and B, we can group by all
the columns except the one we specify:
In [10]: df2=df.set_index(["A","B"])In [11]: grouped=df2.groupby(level=df2.index.names.difference(["B"]))In [12]: grouped.sum()Out[12]: C D
The above GroupBy will split the DataFrame on its index (rows). To split by columns, first do
a transpose:
In [13]: defget_letter_type(letter): ....: ifletter.lower()in'aeiou': ....: return'vowel' ....: else: ....: return'consonant' ....: In [14]: grouped=df.T.groupby(
pandas Index objects support duplicate values. If a
non-unique index is used as the group key in a groupby operation, all values
for the same index value will be considered to be in one group and thus the
output of aggregation functions will only contain unique index values:
In [15]: index=[1,2,3,1,2,3]In [16]: s=pd.Series([1,2,3,10,20,30],index=index
Note that no splitting occurs until it’s needed. Creating the GroupBy object
only verifies that you’ve passed a valid mapping.
GroupBy sorting
By default the group keys are sorted during the groupby operation. You may however pass sort=False for potential speedups. With sort=False the order among group-keys follows the order of appearance of the keys in the original dataframe:
In [22]: df2=pd.DataFrame({"X":["B","B","A","A"],"Y":
GroupBy object attributes
The groups attribute is a dictionary whose keys are the computed unique groups
and corresponding values are the axis labels belonging to each group. In the
above example we have:
Let’s create a Series with a two-level MultiIndex.
In [47]: arrays=[ ....: ["bar","bar","baz","baz","foo","foo","qux","qux"],
Grouping DataFrame with Index levels and columns
A DataFrame may be grouped by a combination of columns and index levels. You
can specify both column and index names, or use a Grouper.
Let’s first create a DataFrame with a MultiIndex:
In [60]: arrays=[ ....: ["bar","bar","baz","baz","foo","foo","qux","qux"],
DataFrame column selection in GroupBy
Once you have created the GroupBy object from a DataFrame, you might want to do
something different for each of the columns. Thus, by using [] on the GroupBy
object in a similar way as the one used to get a column from a DataFrame, you can do:
In [67]: df=pd.DataFrame( ....: { ....: "A":["foo","bar","foo","bar","foo","bar",
Iterating through groups
With the GroupBy object in hand, iterating through the grouped data is very
natural and functions similarly to itertools.groupby():
In [74]: grouped=df.groupby('A')In [75]: forname,groupingrouped: ....: print(name) ....: print(group) ....: bar A B C D1 bar one 0.254161 1.5117633 bar three 0.215897 -0.9905825 bar two -0.077118 1.211526foo A B C D0 foo one -0.575247 1.3460612 foo two -1.143704 1.6270814 foo two 1.193555 -0.4416526 foo one -0.408530 0.2685207 foo three -0.862495 0.024580
In the case of grouping by multiple keys, the group name will be a tuple:
In [76]: forname,groupindf.groupby(['A','B']): ....: print(name) ....: print(group) ....: ('bar', 'one') A B C D1 bar one 0.254161 1.511763('bar', 'three') A B C D3 bar three 0.215897 -0.990582('bar', 'two') A B C D5 bar two -0.077118 1.211526
In [77]: grouped.get_group("bar")Out[77]: A B C D1 bar one 0.254161 1.5117633 bar three 0.215897 -0.9905825 bar two -0.077118 1.211526
Or for an object grouped on multiple columns:
In [78]: df.groupby(["A","B"]).get_group(("bar","one"))Out[78]: A B C D1 bar one 0.254161 1.511763
Aggregation
An aggregation is a GroupBy operation that reduces the dimension of the grouping
object. The result of an aggregation is, or at least is treated as,
a scalar value for each column in a group. For example, producing the sum of each
column in a group of values.
In the result, the keys of the groups appear in the index by default. They can be
instead included in the columns by passing as_index=False.
In [82]: animals.groupby("kind",as_index=False).sum()Out[82]: kind height weight0 cat 18.6 17.81 dog 40.0 205.5
Built-in aggregation methods
Many common aggregations are built-in to GroupBy objects as methods. Of the methods
listed below, those with a * do not have an efficient, GroupBy-specific, implementation.
Any reduction method that pandas implements can be passed as a string to
aggregate(). Users are encouraged to use the shorthand,
agg. It will operate as if the corresponding method was called.
Aggregation with User-Defined Functions
Users can also provide their own User-Defined Functions (UDFs) for custom aggregations.
In [100]: animalsOut[100]: kind height weight
Applying multiple functions at once
On a grouped Series, you can pass a list or dict of functions to
SeriesGroupBy.agg(), outputting a DataFrame:
In [103]: grouped=df.groupby("A")In [104]: grouped["C"].agg(["sum","mean","std"])Out[104]:
Named aggregation
To support column-specific aggregation with control over the output column names, pandas
accepts the special syntax in DataFrameGroupBy.agg() and SeriesGroupBy.agg(), known as “named aggregation”, where
The keywords are the output column names
The values are tuples whose first element is the column to select
and the second element is the aggregation to apply to that column. pandas
provides the NamedAgg namedtuple with the fields ['column','aggfunc']
to make it clearer what the arguments are. As usual, the aggregation can
be a callable or a string alias.
Applying different functions to DataFrame columns
By passing a dict to aggregate you can apply a different aggregation to the
columns of a DataFrame:
In [115]: grouped.agg({"C":"sum","D":lambdax:np.std(x,ddof=1)})Out[115]: C DA
Transformation
A transformation is a GroupBy operation whose result is indexed the same
as the one being grouped. Common examples include cumsum() and
diff().
Similar to the aggregation method, the
transform() method can accept string aliases to the built-in
transformation methods in the previous section. It can also accept string aliases to
the built-in aggregation methods. When an aggregation method is provided, the result
will be broadcast across the group.
In [125]: speedsOut[125]: class order max_speedfalcon bird Falconiformes 389.0parrot bird Psittaciformes 24.0lion mammal Carnivora 80.2monkey mammal Primates NaN
Window and resample operations
It is possible to use resample(), expanding() and
rolling() as methods on groupbys.
The example below will apply the rolling() method on the samples of
the column B, based on the groups of column A.
In [168]: df_re=pd.DataFrame({"A":[1]*10+[
Filtration
A filtration is a GroupBy operation that subsets the original grouping object. It
may either filter out entire groups, part of groups, or both. Filtrations return
a filtered version of the calling object, including the grouping columns when provided.
In the following example, class is included in the result.
In [175]: speedsOut[175]: class order max_speedfalcon bird Falconiformes 389.0parrot bird Psittaciformes 24.0lion mammal Carnivora 80.2monkey mammal Primates NaNleopard mammal Carnivora 58.0In [176]: speeds.groupby("class").nth(1)Out[176]: class order max_speedparrot bird Psittaciformes 24.0monkey mammal Primates NaN
Filtrations will respect subsetting the columns of the GroupBy object.
In [177]: speeds.groupby("class")[["order","max_speed"]].nth(1)Out[177]: order max_speedparrot Psittaciformes 24.0monkey Primates NaN
Built-in filtrations
The following methods on GroupBy act as filtrations. All these methods have an
efficient, GroupBy-specific, implementation.
The filter method takes a User-Defined Function (UDF) that, when applied to
an entire group, returns either True or False. The result of the filter
method is then the subset of groups for which the UDF returned True.
Suppose we want to take only elements that belong to groups with a group sum greater
than 2.
Flexible apply
Some operations on the grouped data might not fit into the aggregation,
transformation, or filtration categories. For these, you can use the apply
function.
In [193]: dfOut[193]: A B C D0 foo one -0.575247 1.3460611 bar one 0.254161 1.5117632 foo two -1.143704 1.6270813 bar three 0.215897 -0.9905824 foo two 1.193555 -0.4416525 bar two -0.077118 1.2115266 foo one -0.408530 0.2685207 foo three -0.862495 0.024580In [194]: grouped=df.groupby("A")# could also just call .describe()In [195]: grouped["C"].apply(lambdax:x.describe())
The dimension of the returned result can also change:
In [196]: grouped=df.groupby('A')['C']In [197]: deff(group): .....: returnpd.DataFrame({'original':group, .....: 'demeaned':group-group.mean()})
apply on a Series can operate on a returned value from the applied function
that is itself a series, and possibly upcast the result to a DataFrame:
In [199]: deff(x): .....: returnpd.Series([x,x**2],index=["x","x^2"]) .....: In [200]: s=pd.Series(np.random.
Similar to The aggregate() method, the resulting dtype will reflect that of the
apply function. If the results from different groups have different dtypes, then
a common dtype will be determined in the same way as DataFrame construction.
Control grouped column(s) placement with group_keys
To control whether the grouped column(s) are included in the indices, you can use
the argument group_keys which defaults to True. Compare
In [203]: df.groupby("A",group_keys=True).apply(lambdax:x,include_groups=
Numba Accelerated Routines
If Numba is installed as an optional dependency, the transform and
aggregate methods support engine='numba' and engine_kwargs arguments.
See enhancing performance with Numba for general usage of the arguments
and performance considerations.
The function signature must start with values,indexexactly as the data belonging to each group
will be passed into values, and the group index will be passed into index.
Other useful features
Exclusion of non-numeric columns
Again consider the example DataFrame we’ve been looking at:
In [205]: dfOut[205]: A B C D0 foo one -0.575247 1.3460611 bar one 0.254161 1.5117632 foo two -1.143704 1.6270813 bar three 0.215897 -0.9905824 foo two 1.193555 -0.4416525 bar two -0.077118 1.2115266 foo one -0.408530 0.2685207 foo three -0.862495 0.024580
Suppose we wish to compute the standard deviation grouped by the A
column. There is a slight problem, namely that we don’t care about the data in
column B because it is not numeric. You can avoid non-numeric columns by
specifying numeric_only=True:
In [206]: df.groupby("A").std(numeric_only=True)Out[206]: C DA bar 0.181231 1.366330foo 0.912265 0.884785
Note that df.groupby('A').colname.std(). is more efficient than
df.groupby('A').std().colname. So if the result of an aggregation function
is only needed over one column (here colname), it may be filtered
before applying the aggregation function.
When using a Categorical grouper (as a single grouper, or as part of multiple groupers), the observed keyword
controls whether to return a cartesian product of all possible groupers values (observed=False) or only those
that are observed groupers (observed=True).
Show all values:
In [210]: pd.Series([1,1,1]).groupby( .....:
NA group handling
By NA, we are referring to any NA values, including
NA, NaN, NaT, and None. If there are any NA values in the
grouping key, by default these will be excluded. In other words, any
“NA group” will be dropped. You can include NA groups by specifying dropna=False.
Grouping with ordered factors
Categorical variables represented as instances of pandas’s Categorical class
can be used as group keys. If so, the order of the levels will be preserved. When
observed=False and sort=False, any unobserved categories will be at the
end of the result in order.
In [218]: days=pd.Categorical( .....: values=["Wed","Mon","Thu","Mon","Wed"
Grouping with a grouper specification
You may need to specify a bit more data to properly group. You can
use the pd.Grouper to provide this local control.
In [223]: importdatetimeIn [224]: df=pd.DataFrame( .....: { .....: "Branch":"A A A A A A A B".split(), .....: "Buyer":"Carl Mark Carl Carl Joe Joe Joe Carl".
Taking the first rows of each group
Just like for a DataFrame or Series you can call head and tail on a groupby:
In [231]: df=pd.DataFrame([[1,2],[1,4],[5,6]],columns=["A","B"])In [232]: dfOut[232]:
Taking the nth row of each group
To select the nth item from each group, use DataFrameGroupBy.nth() or
SeriesGroupBy.nth(). Arguments supplied can be any integer, lists of integers,
slices, or lists of slices; see below for examples. When the nth element of a group
does not exist an error is not raised; instead no corresponding rows are returned.
In general this operation acts as a filtration. In certain cases it will also return
one row per group, making it also a reduction. However because in general it can
return zero or multiple rows per group, pandas treats it as a filtration in all cases.
In [236]: df=pd.DataFrame([[1,
Enumerate group items
To see the order in which each row appears within its group, use the
cumcount method:
In [252]: dfg=pd.DataFrame(list("aaabba"),columns=["A"])In [253]: dfgOut[253]: A0 a1 a2 a3 b4 b5 aIn [254]: dfg
Enumerate groups
To see the ordering of the groups (as opposed to the order of rows
within a group given by cumcount) you can use
DataFrameGroupBy.ngroup().
Note that the numbers given to the groups match the order in which the
groups would be seen when iterating over the groupby object, not the
order they are first observed.
In [256]: dfg=pd.DataFrame(list("aaabba"),columns=["A"])In [257]:
Plotting
Groupby also works with some plotting methods. In this case, suppose we
suspect that the values in column 1 are 3 times higher on average in group “B”.
In [260]: np.random.seed(1234)In [261]: df=pd.DataFrame(np.random.randn(50,2))In [262]: df["g"]
Piping function calls
Similar to the functionality provided by DataFrame and Series, functions
that take GroupBy objects can be chained together using a pipe method to
allow for a cleaner, more readable syntax. To read about .pipe in general terms,
see here.
Combining .groupby and .pipe is often useful when you need to reuse
GroupBy 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 a
multi-step operation, but expressing it in terms of piping can make the
code more readable. First we set the data:
Examples
Multi-column factorization
By using DataFrameGroupBy.ngroup(), we can extract
information about the groups in a way similar to factorize() (as described
further in the reshaping API) but which applies
naturally to multiple columns of mixed type and different
sources. This can be useful as an intermediate categorical-like step
in processing, when the relationships between the group rows are more
important than their content, or as input to an algorithm which only
accepts the integer encoding. (For more information about support in
pandas for full categorical data, see the Categorical
introduction and the
API documentation.)
In [271]: dfg=pd.DataFrame({"A":[1,1,2,3,2],"B":list("aaaba")})In [272]: dfgOut[272]: A B0 1 a1 1 a2 2 a3 3 b4 2 aIn [273]: dfg.groupby(["A"
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 for resample to work on indices that are non-datetimelike, the following procedure can be utilized.
In the following examples, df.index // 5 returns an integer array which is used to determine what gets selected for the groupby operation.
In [275]: df=pd.DataFrame(np.random.
Returning a Series to propagate names
Group DataFrame columns, compute a set of metrics and return a named Series.
The Series name is used as the name for the column index. This is especially
useful in conjunction with reshaping operations such as stacking, in which the
column index name will be used as the name of the inserted column:
In [279]: df=pd.DataFrame( .....: { .....: "a":[0,0,0,0,1,1,1,1
"two"
,
"three"
,
"two"
,
"two"
,
"one"
,
"three"
],
...:
"C"
:
np
.
random
.
randn
(
8
),
...:
"D"
:
np
.
random
.
randn
(
8
),
...:
}
...:
)
...:
In [6]:
df
Out[6]:
A B C D
0 foo one 0.469112 -0.861849
1 bar one -0.282863 -2.104569
2 foo two -1.509059 -0.494929
3 bar three -1.135632 1.071804
4 foo two 1.212112 0.721555
5 bar two -0.173215 -0.706771
6 foo one 0.119209 -1.039575
7 foo three -1.044236 0.271860
A
bar -1.591710 -1.739537
foo -0.752861 -1.402938
get_letter_type
)
)
In [17]:
s
Out[17]:
1 1
2 2
3 3
1 10
2 20
3 30
dtype: int64
In [18]:
grouped
=
s
.
groupby
(
level
=
0
)
In [19]:
grouped
.
first
()
Out[19]:
1 1
2 2
3 3
dtype: int64
In [20]:
grouped
.
last
()
Out[20]:
1 10
2 20
3 30
dtype: int64
In [21]:
grouped
.
sum
()
Out[21]:
1 11
2 22
3 33
dtype: int64
[
1
,
2
,
3
,
4
]})
In [23]:
df2
.
groupby
([
"X"
])
.
sum
()
Out[23]:
Y
X
A 7
B 3
In [24]:
df2
.
groupby
([
"X"
],
sort
=
False
)
.
sum
()
Out[24]:
Y
X
B 3
A 7
Note that groupby will preserve the order in which observations are sorted within each group.
For example, the groups created by groupby() below are in the order they appeared in the original DataFrame:
In [25]: df3=pd.DataFrame({"X":["A","B","A","B"],"Y":[1,4,3,2]})In [26]: df3.groupby("X").get_group("A")Out[26]: X Y0 A 12 A 3In [27]: df3.groupby(["X"]).get_group(("B",))Out[27]: X Y1 B 43 B 2
GroupBy dropna
By default NA values are excluded from group keys during the groupby operation. However,
in case you want to include NA values in group keys, you could pass dropna=False to achieve it.
In [28]: df_list=[[1,2,3],[1,None,4],[2,1,3],[1,2,2]]In [29]: df_dropna=pd.DataFrame(df_list,columns=["a","b","c"])In [30]: df_dropnaOut[30]: a b c0 1 2.0 31 1 NaN 42 2 1.0 33 1 2.0 2
# Default ``dropna`` is set to True, which will exclude NaNs in keysIn [31]: df_dropna.groupby(by=["b"],dropna=True).sum()Out[31]: a cb 1.0 2 32.0 2 5# In order to allow NaN in keys, set ``dropna`` to FalseIn [32]: df_dropna.groupby(by=["b"
The default setting of dropna argument is True which means NA are not included in group keys.
Calling the standard Python len function on the GroupBy object returns
the number of groups, which is the same as the length of the groups dictionary:
If the MultiIndex has names specified, these can be passed instead of the level
number:
In [53]: s.groupby(level="second").sum()Out[53]: secondone 0.980950two 1.991575dtype: float64
Grouping with multiple levels is supported.
In [54]: arrays=[ ....: ["bar","bar","baz","baz","foo","foo","qux","qux"], ....: ["doo","doo","bee","bee","bop","bop","bop","bop"], ....: ["one","two","one","two","one","two","one","two"], ....: ] ....: In [55]: index=pd.MultiIndex.from_arrays(arrays,names=["first","second","third"])In [56]: s=pd.Series(np.random.randn(8),index=index)In [57]: sOut[57]: first second thirdbar doo one -1.131345 two -0.089329baz bee one 0.337863 two -0.945867foo bop one -0.932132 two 1.956030qux bop one 0.017587 two -0.016692dtype: float64In [58]: s.groupby(level=["first","second"]).sum()Out[58]: first secondbar doo -1.220674baz bee -0.608004foo bop 1.023898qux bop 0.000895dtype: float64
Index level names may be supplied as keys.
In [59]: s.groupby(["first","second"]).sum()Out[59]: first secondbar doo -1.220674baz bee -0.608004foo bop 1.023898qux bop 0.000895dtype: float64
More on the sum function and aggregation later.
....:
[
"one"
,
"two"
,
"one"
,
"two"
,
"one"
,
"two"
,
"one"
,
"two"
],
....:
]
....:
In [61]:
index
=
pd
.
MultiIndex
.
from_arrays
(
arrays
,
names
=
[
"first"
,
"second"
])
In [62]:
df
=
pd
.
DataFrame
({
"A"
:
[
1
,
1
,
1
,
1
,
2
,
2
,
3
,
3
],
"B"
:
np
.
arange
(
8
)},
index
=
index
)
In [63]:
df
Out[63]:
A B
first second
bar one 1 0
two 1 1
baz one 1 2
two 1 3
foo one 2 4
two 2 5
qux one 3 6
two 3 7
Then we group df by the second index level and the A column.
In [64]: df.groupby([pd.Grouper(level=1),"A"]).sum()Out[64]: Bsecond A one 1 2 2 4 3 6two 1 4 2 5 3 7
Index levels may also be specified by name.
In [65]: df.groupby([pd.Grouper(level="second"),"A"]).sum()Out[65]: Bsecond A one 1 2 2 4 3 6two 1 4 2 5 3 7
Index level names may be specified as keys directly to groupby.
In [66]: df.groupby(["second","A"]).sum()Out[66]: Bsecond A one 1 2 2 4 3 6two 1 4 2 5 3 7
"foo"
,
"foo"
],
....:
"B"
:
[
"one"
,
"one"
,
"two"
,
"three"
,
"two"
,
"two"
,
"one"
,
"three"
],
....:
"C"
:
np
.
random
.
randn
(
8
),
....:
"D"
:
np
.
random
.
randn
(
8
),
....:
}
....:
)
....:
In [68]:
df
Out[68]:
A B C D
0 foo one -0.575247 1.346061
1 bar one 0.254161 1.511763
2 foo two -1.143704 1.627081
3 bar three 0.215897 -0.990582
4 foo two 1.193555 -0.441652
5 bar two -0.077118 1.211526
6 foo one -0.408530 0.268520
7 foo three -0.862495 0.024580
In [69]:
grouped
=
df
.
groupby
([
"A"
])
In [70]:
grouped_C
=
grouped
[
"C"
]
In [71]:
grouped_D
=
grouped
[
"D"
]
This is mainly syntactic sugar for the alternative, which is much more verbose:
In [72]: df["C"].groupby(df["A"])Out[72]: <pandas.core.groupby.generic.SeriesGroupBy object at 0x7f8c5c5e4460>
Additionally, this method avoids recomputing the internal grouping information
derived from the passed key.
You can also include the grouping columns if you want to operate on them.
In [73]: grouped[["A","B"]].sum()Out[73]: A BA bar barbarbar onethreetwofoo foofoofoofoofoo onetwotwoonethree
In [83]: df.groupby("A")[["C","D"]].max()Out[83]: C DA bar 0.254161 1.511763foo 1.193555 1.627081In [84]: df.groupby(["A","B"]).mean()Out[84]: C DA B bar one 0.254161 1.511763 three 0.215897 -0.990582 two -0.077118 1.211526foo one -0.491888 0.807291 three -0.862495 0.024580 two 0.024925 0.592714
Another aggregation example is to compute the size of each group.
This is included in GroupBy as the size method. It returns a Series whose
index consists of the group names and the values are the sizes of each group.
In [85]: grouped=df.groupby(["A","B"])In [86]: grouped.size()Out[86]: A B bar one 1 three 1 two 1foo one 2 three 1 two 2dtype: int64
While the DataFrameGroupBy.describe() method is not itself a reducer, it
can be used to conveniently produce a collection of summary statistics about each of
the groups.
In [87]: grouped.describe()Out[87]: C ... D count mean std ... 50% 75% maxA B ... bar one 1.0 0.254161 NaN ... 1.511763 1.511763 1.511763 three 1.0 0.215897 NaN ... -0.990582 -0.990582 -0.990582 two 1.0 -0.077118 NaN ... 1.211526 1.211526 1.211526foo one 2.0 -0.491888 0.117887 ... 0.807291 1.076676 1.346061 three 1.0 -0.862495 NaN ... 0.024580 0.024580 0.024580 two 2.0 0.024925 1.652692 ... 0.592714 1.109898 1.627081[6 rows x 16 columns]
Another aggregation example is to compute the number of unique values of each group.
This is similar to the DataFrameGroupBy.value_counts() function, except that it only counts the
number of unique values.
In [88]: ll=[['foo',1],['foo',2],['foo',2],['bar',1],['bar',1]]In [89]: df4=pd.DataFrame(ll,columns=["A","B"])In [90]: df4Out[90]: A B0 foo 11 foo 22 foo 23 bar 14 bar 1In [91]: df4.groupby("A")["B"].nunique()Out[91]: Abar 1foo 2Name: B, dtype: int64
In [92]: grouped=df.groupby("A")In [93]: grouped[["C","D"]].aggregate("sum")Out[93]: C DA bar 0.392940 1.732707foo -1.796421 2.824590In [94]: grouped=df.groupby(["A","B"])In [95]: grouped.agg("sum")Out[95]: C DA B bar one 0.254161 1.511763 three 0.215897 -0.990582 two -0.077118 1.211526foo one -0.983776 1.614581 three -0.862495 0.024580 two 0.049851 1.185429
The result of the aggregation will have the group names as the
new index. In the case of multiple keys, the result is a
MultiIndex by default. As mentioned above, this can be
changed by using the as_index option:
In [96]: grouped=df.groupby(["A","B"],as_index=False)In [97]: grouped.agg("sum")Out[97]: A B C D0 bar one 0.254161 1.5117631 bar three 0.215897 -0.9905822 bar two -0.077118 1.2115263 foo one -0.983776 1.6145814 foo three -0.862495 0.0245805 foo two 0.049851 1.185429In [98]: df.groupby("A",as_index=False)[["C","D"]].agg("sum")Out[98]: A C D0 bar 0.392940 1.7327071 foo -1.796421 2.824590
Note that you could use the DataFrame.reset_index() DataFrame function to achieve
the same result as the column names are stored in the resulting MultiIndex, although
this will make an extra copy.
In [99]: df.groupby(["A","B"]).agg("sum").reset_index()Out[99]: A B C D0 bar one 0.254161 1.5117631 bar three 0.215897 -0.9905822 bar two -0.077118 1.2115263 foo one -0.983776 1.6145814 foo three -0.862495 0.0245805 foo two 0.049851 1.185429
0 cat 9.1 7.9
1 dog 6.0 7.5
2 cat 9.5 9.9
3 dog 34.0 198.0
In [101]:
animals
.
groupby
(
"kind"
)[[
"height"
]]
.
agg
(
lambda
x
:
set
(
x
))
Out[101]:
height
kind
cat {9.1, 9.5}
dog {34.0, 6.0}
The resulting dtype will reflect that of the aggregating function. If the results from different groups have
different dtypes, then a common dtype will be determined in the same way as DataFrame construction.
In [102]: animals.groupby("kind")[["height"]].agg(lambdax:x.astype(int).sum())Out[102]: heightkind cat 18dog 40
sum mean std
A
bar 0.392940 0.130980 0.181231
foo -1.796421 -0.359284 0.912265
On a grouped DataFrame, you can pass a list of functions to
DataFrameGroupBy.agg() to aggregate each
column, which produces an aggregated result with a hierarchical column index:
In [105]: grouped[["C","D"]].agg(["sum","mean","std"])Out[105]: C D sum mean std sum mean stdA bar 0.392940 0.130980 0.181231 1.732707 0.577569 1.366330foo -1.796421 -0.359284 0.912265 2.824590 0.564918 0.884785
The resulting aggregations are named after the functions themselves. If you
need to rename, then you can add in a chained operation for a Series like this:
In [106]: ( .....: grouped["C"] .....: .agg(["sum","mean","std"]) .....: .rename(columns={"sum":"foo","mean":"bar","std":"baz"}) .....: ) .....: Out[106]: foo bar bazA bar 0.392940 0.130980 0.181231foo -1.796421 -0.359284 0.912265
For a grouped DataFrame, you can rename in a similar manner:
In [107]: ( .....: grouped[["C","D"]].agg(["sum","mean","std"]).rename( .....: columns={"sum":"foo","mean":"bar","std":"baz"} .....: ) .....: ) .....: Out[107]: C D foo bar baz foo bar bazA bar 0.392940 0.130980 0.181231 1.732707 0.577569 1.366330foo -1.796421 -0.359284 0.912265 2.824590 0.564918 0.884785
If the column names you want are not valid Python keywords, construct a dictionary
and unpack the keyword arguments
In [113]: animals.groupby("kind").agg( .....: **{ .....: "total weight":pd.NamedAgg(column="weight",aggfunc="sum") .....: } .....: ) .....: Out[113]: total weightkind cat 17.8dog 205.5
When using named aggregation, additional keyword arguments are not passed through
to the aggregation functions; only pairs
of (column,aggfunc) should be passed as **kwargs. If your aggregation functions
require additional arguments, apply them partially with functools.partial().
Named aggregation is also valid for Series groupby aggregations. In this case there’s
no column selection, so the values are just the functions.
In addition, passing any built-in aggregation method as a string to
transform() (see the next section) will broadcast the result
across the group, producing a transformed result. If the aggregation method has an efficient
implementation, this will be performant as well.
leopard mammal Carnivora 58.0
In [126]:
grouped
=
speeds
.
groupby
(
"class"
)[[
"max_speed"
]]
In [127]:
grouped
.
transform
(
"cumsum"
)
Out[127]:
max_speed
falcon 389.0
parrot 413.0
lion 80.2
monkey NaN
leopard 138.2
In [128]:
grouped
.
transform
(
"sum"
)
Out[128]:
max_speed
falcon 413.0
parrot 413.0
lion 138.2
monkey 138.2
leopard 138.2
In addition to string aliases, the transform() method can
also accept User-Defined Functions (UDFs). The UDF must:
Return a result that is either the same size as the group chunk or
broadcastable to the size of the group chunk (e.g., a scalar,
grouped.transform(lambdax:x.iloc[-1])).
Operate column-by-column on the group chunk. The transform is applied to
the first group chunk using chunk.apply.
Not perform in-place operations on the group chunk. Group chunks should
be treated as immutable, and changes to a group chunk may produce unexpected
results. See Mutating with User Defined Function (UDF) methods for more information.
(Optionally) operates on all columns of the entire group chunk at once. If this is
supported, a fast path is used starting from the second chunk.
Similar to The aggregate() method, the resulting dtype will reflect that of the
transformation function. If the results from different groups have different dtypes, then
a common dtype will be determined in the same way as DataFrame construction.
Suppose we wish to standardize the data within each group:
We can verify that the group means have not changed in the transformed data,
and that the transformed data contains no NAs.
In [156]: grouped_trans=transformed.groupby(key)In [157]: grouped.mean()# original group meansOut[157]: A B CGR -0.098371 -0.015420 0.068053JP 0.069025 0.023100 -0.077324UK 0.034069 -0.052580 -0.116525US 0.058664 -0.020399 0.028603In [158]: grouped_trans.mean()# transformation did not change group meansOut[158]: A B CGR -0.098371 -0.015420 0.068053JP 0.069025 0.023100 -0.077324UK 0.034069 -0.052580 -0.116525US 0.058664 -0.020399 0.028603In [159]: grouped.count()# original has some missing data pointsOut[159]: A B CGR 209 217 189JP 240 255 217UK 216 231 193US 239 250 217In [160]: grouped_trans.count()# counts after transformationOut[160]: A B CGR 228 228 228JP 267 267 267UK 247 247 247US 258 258 258In [161]: grouped_trans.size()# Verify non-NA count equals group sizeOut[161]: GR 228JP 267UK 247US 258dtype: int64
As mentioned in the note above, each of the examples in this section can be computed
more efficiently using built-in methods. In the code below, the inefficient way
using a UDF is commented out and the faster alternative appears below.
The expanding() method will accumulate a given operation
(sum() in the example) for all the members of each particular
group.
In [171]: df_re.groupby("A").expanding().sum()Out[171]: BA 1 0 0.0 1 1.0 2 3.0 3 6.0 4 10.0... ...5 15 75.0 16 91.0 17 108.0 18 126.0 19 145.0[20 rows x 1 columns]
Suppose you want to use the resample() method to get a daily
frequency in each group of your dataframe, and wish to complete the
missing values with the ffill() method.
Users can also use transformations along with Boolean indexing to construct complex
filtrations within groups. For example, suppose we are given groups of products and
their volumes, and we wish to subset the data to only the largest products capturing no
more than 90% of the total volume within each group.
In [178]: product_volumes=pd.DataFrame( .....: { .....: "group":list("xxxxyyy"), .....: "product":list("abcdefg"), .....: "volume":[10,30,20,15,40,10,20], .....: } .....: ) .....: In [179]: product_volumesOut[179]: group product volume0 x a 101 x b 302 x c 203 x d 154 y e 405 y f 106 y g 20# Sort by volume to select the largest products firstIn [180]: product_volumes=product_volumes.sort_values("volume",ascending=False)In [181]: grouped=product_volumes.groupby("group")["volume"]In [182]: cumpct=grouped.cumsum()/grouped.transform("sum")In [183]: cumpctOut[183]: 4 0.5714291 0.4000002 0.6666676 0.8571433 0.8666670 1.0000005 1.000000Name: volume, dtype: float64In [184]: significant_products=product_volumes[cumpct<=0.9]In [185]: significant_products.sort_values(["group","product"])Out[185]: group product volume1 x b 302 x c 203 x d 154 y e 406 y g 20
In [186]: sf=pd.Series([1,1,2,3,3,3])In [187]: sf.groupby(sf).filter(lambdax:x.sum()>2)Out[187]: 3 34 35 3dtype: int64
Another useful operation is filtering out elements that belong to groups
with only a couple members.
In [188]: dff=pd.DataFrame({"A":np.arange(8),"B":list("aabbbbcc")})In [189]: dff.groupby("B").filter(lambdax:len(x)>2)Out[189]: A B2 2 b3 3 b4 4 b5 5 b
Alternatively, instead of dropping the offending groups, we can return a
like-indexed objects where the groups that do not pass the filter are filled
with NaNs.
In [190]: dff.groupby("B").filter(lambdax:len(x)>2,dropna=False)Out[190]: A B0 NaN NaN1 NaN NaN2 2.0 b3 3.0 b4 4.0 b5 5.0 b6 NaN NaN7 NaN NaN
For DataFrames with multiple columns, filters should explicitly specify a column as the filter criterion.
In [191]: dff["C"]=np.arange(8)In [192]: dff.groupby("B").filter(lambdax:len(x["C"])>2)Out[192]: A B C2 2 b 23 3 b 34 4 b 45 5 b 5
Out[195]:
A
bar count 3.000000
mean 0.130980
std 0.181231
min -0.077118
25% 0.069390
...
foo min -1.143704
25% -0.862495
50% -0.575247
75% -0.408530
max 1.193555
Name: C, Length: 16, dtype: float64
.....:
In [198]:
grouped
.
apply
(
f
)
Out[198]:
original demeaned
A
bar 1 0.254161 0.123181
3 0.215897 0.084917
5 -0.077118 -0.208098
foo 0 -0.575247 -0.215962
2 -1.143704 -0.784420
4 1.193555 1.552839
6 -0.408530 -0.049245
7 -0.862495 -0.503211
rand
(
5
))
In [201]:
s
Out[201]:
0 0.582898
1 0.098352
2 0.001438
3 0.009420
4 0.815826
dtype: float64
In [202]:
s
.
apply
(
f
)
Out[202]:
x x^2
0 0.582898 0.339770
1 0.098352 0.009673
2 0.001438 0.000002
3 0.009420 0.000089
4 0.815826 0.665572
False
)
Out[203]:
B C D
A
bar 1 one 0.254161 1.511763
3 three 0.215897 -0.990582
5 two -0.077118 1.211526
foo 0 one -0.575247 1.346061
2 two -1.143704 1.627081
4 two 1.193555 -0.441652
6 one -0.408530 0.268520
7 three -0.862495 0.024580
with
In [204]: df.groupby("A",group_keys=False).apply(lambdax:x,include_groups=False)Out[204]: B C D0 one -0.575247 1.3460611 one 0.254161 1.5117632 two -1.143704 1.6270813 three 0.215897 -0.9905824 two 1.193555 -0.4416525 two -0.077118 1.2115266 one -0.408530 0.2685207 three -0.862495 0.024580
3
,
4
],
.....:
"dec_column"
:
[
.....:
Decimal
(
"0.50"
),
.....:
Decimal
(
"0.15"
),
.....:
Decimal
(
"0.25"
),
.....:
Decimal
(
"0.40"
),
.....:
],
.....:
}
.....:
)
.....:
In [209]:
df_dec
.
groupby
([
"id"
])[[
"dec_column"
]]
.
sum
()
Out[209]:
dec_column
id
1 0.75
2 0.55
pd
.
Categorical
([
"a"
,
"a"
,
"a"
],
categories
=
[
"a"
,
"b"
]),
observed
=
False
.....:
)
.
count
()
.....:
Out[210]:
a 3
b 0
dtype: int64
Show only the observed values:
In [211]: pd.Series([1,1,1]).groupby( .....: pd.Categorical(["a","a","a"],categories=["a","b"]),observed=True .....: ).count() .....: Out[211]: a 3dtype: int64
The returned dtype of the grouped will always include all of the categories that were grouped.
In [212]: s=( .....: pd.Series([1,1,1]) .....: .groupby(pd.Categorical(["a","a","a"],categories=["a","b"]),observed=True) .....: .count() .....: ) .....: In [213]: s.index.dtypeOut[213]: CategoricalDtype(categories=['a', 'b'], ordered=False, categories_dtype=object)
In [214]: df=pd.DataFrame({"key":[1.0,1.0,np.nan,2.0,np.nan],"A":[1,2,3,4,5]})In [215]: dfOut[215]: key A0 1.0 11 1.0 22 NaN 33 2.0 44 NaN 5In [216]: df.groupby("key",dropna=True).sum()Out[216]: Akey 1.0 32.0 4In [217]: df.groupby("key",dropna=False).sum()Out[217]: Akey 1.0 32.0 4NaN 8
,
"Sat"
],
.....:
categories
=
[
"Mon"
,
"Tue"
,
"Wed"
,
"Thu"
,
"Fri"
,
"Sat"
,
"Sun"
],
.....:
)
.....:
In [219]:
data
=
pd
.
DataFrame
(
.....:
{
.....:
"day"
:
days
,
.....:
"workers"
:
[
3
,
4
,
1
,
4
,
2
,
2
],
.....:
}
.....:
)
.....:
In [220]:
data
Out[220]:
day workers
0 Wed 3
1 Mon 4
2 Thu 1
3 Mon 4
4 Wed 2
5 Sat 2
In [221]:
data
.
groupby
(
"day"
,
observed
=
False
,
sort
=
True
)
.
sum
()
Out[221]:
workers
day
Mon 8
Tue 0
Wed 5
Thu 1
Fri 0
Sat 2
Sun 0
In [222]:
data
.
groupby
(
"day"
,
observed
=
False
,
sort
=
False
)
.
sum
()
Out[222]:
workers
day
Wed 5
Mon 8
Thu 1
Sat 2
Tue 0
Fri 0
Sun 0
split
(),
.....:
"Quantity"
:
[
1
,
3
,
5
,
1
,
8
,
1
,
9
,
3
],
.....:
"Date"
:
[
.....:
datetime
.
datetime
(
2013
,
1
,
1
,
13
,
0
),
.....:
datetime
.
datetime
(
2013
,
1
,
1
,
13
,
5
),
.....:
datetime
.
datetime
(
2013
,
10
,
1
,
20
,
0
),
.....:
datetime
.
datetime
(
2013
,
10
,
2
,
10
,
0
),
.....:
datetime
.
datetime
(
2013
,
10
,
1
,
20
,
0
),
.....:
datetime
.
datetime
(
2013
,
10
,
2
,
10
,
0
),
.....:
datetime
.
datetime
(
2013
,
12
,
2
,
12
,
0
),
.....:
datetime
.
datetime
(
2013
,
12
,
2
,
14
,
0
),
.....:
],
.....:
}
.....:
)
.....:
In [225]:
df
Out[225]:
Branch Buyer Quantity Date
0 A Carl 1 2013-01-01 13:00:00
1 A Mark 3 2013-01-01 13:05:00
2 A Carl 5 2013-10-01 20:00:00
3 A Carl 1 2013-10-02 10:00:00
4 A Joe 8 2013-10-01 20:00:00
5 A Joe 1 2013-10-02 10:00:00
6 A Joe 9 2013-12-02 12:00:00
7 B Carl 3 2013-12-02 14:00:00
Groupby a specific column with the desired frequency. This is like resampling.
In [226]: df.groupby([pd.Grouper(freq="1ME",key="Date"),"Buyer"])[["Quantity"]].sum()Out[226]: QuantityDate Buyer 2013-01-31 Carl 1 Mark 32013-10-31 Carl 6 Joe 92013-12-31 Carl 3 Joe 9
When freq is specified, the object returned by pd.Grouper will be an
instance of pandas.api.typing.TimeGrouper. When there is a column and index
with the same name, you can use key to group by the column and level
to group by the index.
In [227]: df=df.set_index("Date")In [228]: df["Date"]=df.index+pd.offsets.MonthEnd(2)In [229]: df.groupby([pd.Grouper(freq="6ME",key="Date"),"Buyer"])[["Quantity"]].sum()Out[229]: QuantityDate Buyer 2013-02-28 Carl 1 Mark 32014-02-28 Carl 9 Joe 18In [230]: df.groupby([pd.Grouper(freq="6ME",level="Date"),"Buyer"])[["Quantity"]].sum()Out[230]: QuantityDate Buyer 2013-01-31 Carl 1 Mark 32014-01-31 Carl 9 Joe 18
A B
0 1 2
1 1 4
2 5 6
In [233]:
g
=
df
.
groupby
(
"A"
)
In [234]:
g
.
head
(
1
)
Out[234]:
A B
0 1 2
2 5 6
In [235]:
g
.
tail
(
1
)
Out[235]:
A B
1 1 4
2 5 6
This shows the first or last n rows from each group.
np
.
nan
],
[
1
,
4
],
[
5
,
6
]],
columns
=
[
"A"
,
"B"
])
In [237]:
g
=
df
.
groupby
(
"A"
)
In [238]:
g
.
nth
(
0
)
Out[238]:
A B
0 1 NaN
2 5 6.0
In [239]:
g
.
nth
(
-
1
)
Out[239]:
A B
1 1 4.0
2 5 6.0
In [240]:
g
.
nth
(
1
)
Out[240]:
A B
1 1 4.0
If the nth element of a group does not exist, then no corresponding row is included
in the result. In particular, if the specified n is larger than any group, the
result will be an empty DataFrame.
In [241]: g.nth(5)Out[241]: Empty DataFrameColumns: [A, B]Index: []
If you want to select the nth not-null item, use the dropna kwarg. For a DataFrame this should be either 'any' or 'all' just like you would pass to dropna:
# nth(0) is the same as g.first()In [242]: g.nth(0,dropna="any")Out[242]: A B1 1 4.02 5 6.0In [243]: g.first()Out[243]: BA 1 4.05 6.0# nth(-1) is the same as g.last()In [244]: g.nth(-1,dropna="any")Out[244]: A B1 1 4.02 5 6.0In [245]: g.last()Out[245]: BA 1 4.05 6.0In [246]: g.B.nth(0,dropna="all")Out[246]: 1 4.02 6.0Name: B, dtype: float64
You can also select multiple rows from each group by specifying multiple nth values as a list of ints.
In [247]: business_dates=pd.date_range(start="4/1/2014",end="6/30/2014",freq="B")In [248]: df=pd.DataFrame(1,index=business_dates,columns=["a","b"])# get the first, 4th, and last date index for each monthIn [249]: df.groupby([df.index.year,df.index.month]).nth([0,3,-1])Out[249]: a b2014-04-01 1 12014-04-04 1 12014-04-30 1 12014-05-01 1 12014-05-06 1 12014-05-30 1 12014-06-02 1 12014-06-05 1 12014-06-30 1 1
In [264]: df.groupby("g").boxplot()Out[264]: A Axes(0.1,0.15;0.363636x0.75)B Axes(0.536364,0.15;0.363636x0.75)dtype: object
The result of calling boxplot is a dictionary whose keys are the values
of our grouping column g (“A” and “B”). The values of the resulting dictionary
can be controlled by the return_type keyword of boxplot.
See the visualization documentation for more.
Here mean takes a GroupBy object and finds the mean of the Revenue and Quantity
columns respectively for each Store-Product combination. The mean function can
be any function that takes in a GroupBy object; the .pipe will pass the GroupBy
object as a parameter into the function you specify.