Pandas dataframe group by column and apply min, max, average on different columns

Advertisements

I am looking a way to transform this dataframe below

itemid  clock   value_min   value_avg   value_max   item_type
A1  27/05/2021    4             7           38          cpu
A2  27/05/2021    4             5           15          mem
B1  27/05/2021    1             2           5           cpu
B2  27/05/2021    3             20          86          mem
A1  28/05/2021    8             8           9           cpu
A2  28/05/2021    1             2           5           mem
B1  28/05/2021    0             1           2           cpu
B2  28/05/2021    4             7           8           mem

to

itemid  value_min   value_avg   value_max   item_type
A1       4           7,5          38           cpu
A2       1           3,5          15           mem
B1       0           0,5           5           cpu
B2       3           3,5          86           mem

I want to group by itemid and then apply the rules

  • where column value_min is the min,
  • where column value_avg is the mean
  • where column value_max is the max

>Solution :

this should answer your question:

df = df.groupby('itemid').agg({'value_min': 'min', 'value_avg': 'mean', 'value_max': 'max', 'item_type': 'first'})

Leave a ReplyCancel reply