简体   繁体   中英

Pandas: Group by and aggregation with function

Assuming that I have a dataframe with the following values:

    name     start    end     description
0    ag       20       30       None
1    bgb      21       111      'a'
2    cdd      31       101      None
3    bgb      17       19       'Bla'
4    ag       20       22       None

I want to groupby name and then get average of ( end - start ) values.

I can use mean ( df.groupby(['name'], as_index=False).mean() )

but how can I give the mean function the subtraction of two columns (last - first) ?

You can subtract column and then grouping by column df['name'] :

df1 = df['end'].sub(df['start']).groupby(df['name']).mean().reset_index(name='diff')
print (df1)
 name  diff
0   ag     6
1  bgb    46
2  cdd    70

Another idea with new column diff :

df1 = (df.assign(diff = df['end'].sub(df['start']))
         .groupby('name', as_index=False)['diff']
         .mean())
print (df1)
  name  diff
0   ag     6
1  bgb    46
2  cdd    70

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM