Reputation: 693
I'd like to use groupby, but instead of applying the same functions to each group, I want to specify which function to apply to which group value. I'm providing a very simple example here to illustrate the point, but in reality there are many values of my groupby variable, and my functions are all user-defined and fairly complex -- so solutions that involve selecting each group separately or apply the same functions to all groups will not be practical. (Answers of that sort were provided to this very similar question: how to apply different functions to each group of pandas groupby? but they don't address my question)
df = DataFrame({'Category': ['A','A','A','B','B','B','C','C','C'],
'Total': [1, 2, 3, 1, 2, 3, 1, 2, 3]})
I'd like to be able to specify a function for each level of my groupby variable:
function_map = {'A': np.mean,
'B': np.max,
'C': np.min}
What I would like to be able to do is something like this:
df.groupby('Category').apply(function_map)
And the form of result I want would look like this DataFrame:
result = DataFrame({'Category': ['A','B','C'],
'Total': [2, 3, 1]})
Upvotes: 1
Views: 243
Reputation: 9946
just use a lambda, something like this
df.groupby('Category').apply(lambda r: function_map[r.name](r.Total))
also, you should use numpy
functions so np.mean
, np.max
, np.min
Upvotes: 2