pandas: GroupBy .pipe() vs .apply() pandas: GroupBy .pipe() vs .apply() python-3.x python-3.x

pandas: GroupBy .pipe() vs .apply()


What pipe does is to allow you to pass a callable with the expectation that the object that called pipe is the object that gets passed to the callable.

With apply we assume that the object that calls apply has subcomponents that will each get passed to the callable that was passed to apply. In the context of a groupby the subcomponents are slices of the dataframe that called groupby where each slice is a dataframe itself. This is analogous for a series groupby.

The main difference between what you can do with a pipe in a groupby context is that you have available to the callable the entire scope of the the groupby object. For apply, you only know about the local slice.

Setup
Consider df

df = pd.DataFrame(dict(    A=list('XXXXYYYYYY'),    B=range(10)))   A  B0  X  01  X  12  X  23  X  34  Y  45  Y  56  Y  67  Y  78  Y  89  Y  9

Example 1
Make the entire 'B' column sum to 1 while each sub-group sums to the same amount. This requires that the calculation be aware of how many groups exist. This is something we can't do with apply because apply wouldn't know how many groups exist.

s = df.groupby('A').B.pipe(lambda g: df.B / g.transform('sum') / g.ngroups)s0    0.0000001    0.0833332    0.1666673    0.2500004    0.0512825    0.0641036    0.0769237    0.0897448    0.1025649    0.115385Name: B, dtype: float64

Note:

s.sum()0.99999999999999989

And:

s.groupby(df.A).sum()AX    0.5Y    0.5Name: B, dtype: float64

Example 2
Subtract the mean of one group from the values of another. Again, this can't be done with apply because apply doesn't know about other groups.

df.groupby('A').B.pipe(    lambda g: (        g.get_group('X') - g.get_group('Y').mean()    ).append(        g.get_group('Y') - g.get_group('X').mean()    ))0   -6.51   -5.52   -4.53   -3.54    2.55    3.56    4.57    5.58    6.59    7.5Name: B, dtype: float64