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 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, which contrasts with transform
and agg
that get called once for each non-grouping column. 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.
Getting ready
In this recipe, we calculate the weighted average of both the math and verbal SAT scores per state from the...