Apply function func group-wise and combine the results together.
The function passed to apply must take a dataframe as its first
argument and return a DataFrame, Series or scalar. apply will
then take care of combining the results back together into a single
dataframe or series. is therefore a highly flexible
grouping method.
apply
While apply is a very flexible method, its downside is that
using it can be quite a bit slower than using more specific methods
like agg or transform. Pandas offers a wide range of method that will
be much faster than using apply for their specific purposes, so try to
use them before reaching for apply.
Parameters:
func : callable
A callable that takes a dataframe as its first argument, and
returns a dataframe, a series or a scalar. In addition the
callable may take positional and keyword arguments.
include_groups : bool, default True
When True, will attempt to apply func to the groupings in
the case that they are columns of the DataFrame. If this raises a
TypeError, the result will be computed with the groupings excluded.
When False, the groupings will be excluded when applying func.
args, kwargs : tuple and dict
Optional positional and keyword arguments to pass to func.
>>> df=pd.DataFrame({'A':'a a b'.split(),... 'B':[1,2,3],... 'C':[4,6,5]})>>> g1=df.groupby('A',group_keys=False)>>> g2=df.groupby('A',group_keys=True)
Notice that g1 and g2 have two groups, a and b, and only
differ in their group_keys argument. Calling apply in various ways,
we can get different grouping results:
Example 1: below the function passed to apply takes a DataFrame as
its argument and returns a DataFrame. apply combines the result for
each group together into a new DataFrame:
>>> g1[['B','C']].apply(lambdax:x/x.sum()) B C0 0.333333 0.41 0.666667 0.62 1.000000 1.0
In the above, the groups are not part of the index. We can have them included
by using g2 where group_keys=True:
Example 2: The function passed to apply takes a DataFrame as
its argument and returns a Series. apply combines the result for
each group together into a new DataFrame.
>>> g1[['B','C']].apply(lambdax:x.astype(float).max()-x.min()) B CAa 1.0 2.0b 0.0 0.0
>>> g2[['B','C']].apply(lambdax:x.astype(float).max()-x.min()) B CAa 1.0 2.0b 0.0 0.0
The group_keys argument has no effect here because the result is not
like-indexed (i.e. a transform) when compared
to the input.
Example 3: The function passed to apply takes a DataFrame as
its argument and returns a scalar. apply combines the result for
each group together into a Series, including setting the index as
appropriate: