This is what I want to achieve:
input:
B C D
A
x z 1 10
x z 2 11
x z 3 12
y s 4 13
y s 5 14
output:
B C D sum
A
x z 3 12 33
y s 5 14 27
I have the following code.
import pandas as pd
df = pd.DataFrame({'A': ['x','x','x','y','y'],
'B': ['z','z','z','s','s'],
'C': [1,2,3,4,5],
'D': [10,11,12,13,14]})
df = df.set_index('A')
df['sum'] = df.groupby('A')['D'].transform('sum')
idx = df.groupby(['A'])['C'].transform(max) == df['C']
df= df[idx]
I am doing this on a fairly large Dataframe. However it takes very long, especially the first group by. Is there any way to speed up that process? Since all I am trying to do is take the sum over a group and keep the row where a different column is max.
