Customizing aggregating functions with *args and **kwargs
When writing your own user-defined customized aggregation function, pandas implicitly passes it each of the aggregating columns one at a time as a Series. Occasionally, you will need to pass more arguments to your function than just the Series itself. To do so, you need to be aware of Python's ability to pass an arbitrary number of arguments to functions. Let's take a look at the signature of the groupby object's agg
method with help from the inspect
module:
>>> college = pd.read_csv('data/college.csv') >>> grouped = college.groupby(['STABBR', 'RELAFFIL']) >>> import inspect >>> inspect.signature(grouped.agg) <Signature (arg, *args, **kwargs)>
The argument *args
allow you to pass an arbitrary number of non-keyword arguments to your customized aggregation function. Similarly, **kwargs
allows you to pass an arbitrary number of keyword arguments.
Getting ready
In this recipe, we build a customized...