简体   繁体   中英

Pandas use groupby to apply a different function for each value of the groupby variable

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]})

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM