我想对我的.groupby结果中的每个组应用一个函数,我的原始df如下所示:
Id Cust_type DPP
1 A Detractor
2 B Detractor
3 C Detractor
4 D Promoter
5 A Promoter
6 B Passive
7 B Detractor
8 C Detractor
9 D Detractor
10 D Promoter
11 A Promoter
12 A Passive
我想计算每种Cust_type的得分,完整df的得分计算如下:
((len(df[df['DPP']=='Promoters'])-len(df[df['DPP']=='Detractors']))/(len(df)))*100
因此,我尝试定义一个函数,然后将其应用于每个组,但下面的方法不起作用,因为我真的不知道如何做。
def score(x):
return ((len(x[x['DPP']=='Promoters'])-len(x[x['DPP']=='Detractors']))/(len(x)))*100
df.groupby('Cust_type').apply(score, x))
任何帮助都感激不尽。
2条答案
按热度按时间4si2a6ki1#
您的代码中有许多语法错误。
下面是一个稍微简化的版本:
或者,由于只使用单个列:
输出:
另一种方法:
4nkexdtk2#