I have a DataFrame like this:
df = pd.DataFrame({'id':['pt1','px1','t95','sx1','dc4','px5'],
'group':['f7','f7', 'f7','f8','f8','f8'],
'score':['2','3.3','4','8','4.9','6']})
I want to add another column and calculate the difference between each score in each group with the maximum score of that group. The expected result would be:
group id score score_diff
f7 pt1 2 -2
f7 px1 3.3 -.7
f7 t95 4 0
f8 sx1 8 0
f8 dc4 4.9 -3.1
f8 px5 6 -2
Would appreciate if you could please help. I want to run the code on 2000+ records. Below is my code but it gives me score difference from the previous record in each group. however, I want to calculate the score difference from max score in each group.
result = df.groupby(['fk'])['score'].diff()