Skip to content Skip to sidebar Skip to footer

Apply Different Functions To Different Columns With A Singe Pandas Groupby Command

My data is stored in df. I have multiple users per group. I want to group df by group and apply different functions to different columns. The twist is that I would like to assign c

Solution 1:

Try creating a function with the required operations using groupby().apply():

def f(x):
    d = {}
    d['mean_score'] = x['score'].mean()
    d['min_crop'] = x['crop'].min()
    d['max_crop'] = x['crop'].max()
    return pd.Series(d, index=['mean_score', 'min_crop', 'max_crop'])

data = df.groupby('group').apply(f)

Post a Comment for "Apply Different Functions To Different Columns With A Singe Pandas Groupby Command"