Search code examples
pythonpandasgroup-bypandas-groupby

pandas groupby add and average at the same time


I have a data frame with a list of processes and the time they took as follows

enter image description here

I would like to get the following result

enter image description here

I know how to use gorupby in order to get ONE but only one of those columns. And this is the way I solve the problem

# the data
ps    = ['p1','p2','p3','p4','p2','p2','p3','p6','p2','p4','p5','p6']
times = [20,10,2,3,4,5,6,3,4,5,6,7]
processes = pd.DataFrame({'ps':ps,'time':times})

# the series
dfsum   = processes.groupby('PROCESS')['TIME'].sum()
dfcount = processes.groupby('PROCESS')['TIME'].count()

# "building" the df result
frame = { 'total_time': dfsum, 'total_nr': dfcount} 
dfresult = pd.DataFrame(frame)
dfresult['average']= dfresult['total_time']/dfresult['total_nr']
dfresult

but how to get the desired df without having to compose it column by column? For me this method is not "pandonic" enough (nor pythonic)


Solution

  • processes.groupby('ps').agg(TOTAL_TIME=('time','sum'),AVERAGE=('time','mean'),NRTIMES=('time','size'))