如何将多个聚合函数应用于具有不同groupby的同一列?

2024-05-18 14:49:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在建立一些关于熊猫的报告,我想包括与整体价值的比较

假设我们有:

import pandas

data = {'puppy_name': ['Stanley', 'Doggo', 'Stanley', 'Doggo','Stanley', 'Doggo', 'Stanley', 'Doggo'],
'treats_earned': [25, 15, 20, 30, 20, 25, 20, 35],
'month': ['feb', 'feb', 'feb', 'feb','mar', 'mar', 'mar', 'mar']}

df = pandas.DataFrame(data)

我想展示的是:

pup     / month / pup_avg / overall_month_avg
Stanley | feb   | 22.5    | 22.5
Doggo   | feb   | 20      | 22.5
Stanley | mar   | 20      | 25
Doggo   | mar   | 27.5    | 25

因此,对于一列,我们按['month','pup']分组/表示,对于另一列,我们按['month']分组/表示


Tags: nameimportpandasdata报告marfebavg
1条回答
网友
1楼 · 发布于 2024-05-18 14:49:48

我们需要groupby两次和map

s=df.groupby(['puppy_name','month'])['treats_earned'].mean().reset_index()
s['overall_month_avg']=s['month'].map(df.groupby('month')['treats_earned'].mean())
s
Out[33]: 
  puppy_name month  treats_earned  overall_month_avg
0      Doggo   feb           22.5               22.5
1      Doggo   mar           30.0               25.0
2    Stanley   feb           22.5               22.5
3    Stanley   mar           20.0               25.0

相关问题 更多 >

    热门问题