Calculating weighted mean SAT scores per state with apply
The groupby
object has four methods that accept a function (or functions) to perform a calculation on each group. These four methods are .agg
, .filter
, .transform
, and .apply
. Each of the first three of these methods has a very specific output that the function must return. .agg
must return a scalar value, .filter
must return a Boolean, and .transform
must return a Series or DataFrame with the same length as the passed group. The .apply
method, however, may return a scalar value, a Series, or even a DataFrame of any shape, therefore making it very flexible. It is also called only once per group (on a DataFrame), while the .transform
and .agg
methods get called once for each aggregating column (on a Series). The .apply
method's ability to return a single object when operating on multiple columns at the same time makes the calculation in this recipe possible.
In this recipe, we calculate the weighted average of both...