Pandas resample apply function on whole rows?

Viewed 598

Is it somehow possible to get the rows of a resample operation to apply a custom function:

Let's assume we have a DataFrame df that contains for instance birthdays of children and their names and the number of friends they have:

birthday    name   friends
datetime_1  Alice  10
datetime_2  Bob    5
   ...      ...    ...
datetime_n  Tom    12

If we now resample by some time frequency and try to apply a custom function:

df.resample("w").apply(my_func)

It will only pass the input as separate series and not as rows. There is no axis argument in the case of Resampler.apply. So would there be any way to achieve something like I want. Or is there another built-in way that could be used to build custom behaviour into the reduction part? For example if I would want to return the most frequent name weighted by the number of friends that name is associated with in a given time interval.

1 Answers

Ah, ok. What you need is grouper to be able to use groupby.

df.groupby(pd.Grouper(freq='W')).apply(my_func)

Hope, that's it.

Related