Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groupby and find difference from min value of group : Pandas

I have a group like following, how can I know the difference of every observation with it's group minimum value

GROUP VALUE
 1     5
 2     2
 1     10
 2     20
 1     7

So, my desired output should be like

GROUP VALUE diff
 1     5    3
 2     2    0
 1     10   5
 2     20  18
 1     7    5

How can I achieve it with the help of pandas

Thanks for all the help

like image 675
Manu Sharma Avatar asked Feb 18 '19 08:02

Manu Sharma


1 Answers

I think you need GroupBy.transform with subtract:

df['diff'] = df['VALUE'] - df.groupby('GROUP')['VALUE'].transform('min')
print (df)
   GROUP  VALUE  diff
0      1      5     0
1      2      2     0
2      1     10     5
3      2     20    18
4      1      7     2
like image 71
jezrael Avatar answered Nov 17 '22 10:11

jezrael