pandas 将函数应用于groupby中的每个组

bgtovc5b  于 2023-01-11  发布在  其他
关注(0)|答案(2)|浏览(168)

我想对我的.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))

任何帮助都感激不尽。

4si2a6ki

4si2a6ki1#

您的代码中有许多语法错误。
下面是一个稍微简化的版本:

def score(x):
    return (x['DPP'].eq('Promoter').sum()-x['DPP'].eq('Detractor').sum())/len(x)*100

df.groupby('Cust_type').apply(score)

或者,由于只使用单个列:

def score(x):
    return (x.eq('Promoter').sum()-x.eq('Detractor').sum())/len(x)*100

df.groupby('Cust_type')['DPP'].apply(score)

输出:

Cust_type
A     25.000000
B    -66.666667
C   -100.000000
D     33.333333
Name: DPP, dtype: float64

另一种方法:

d = {'Promoter': 1, 'Detractor': -1}

df['DPP'].map(d).fillna(0).groupby(df['Cust_type']).mean().mul(100)
4nkexdtk

4nkexdtk2#

df2=pd.crosstab(df1.Cust_type,df1.DPP,normalize='index')
df2.Promoter.sub(df2.Detractor).mul(100)

out:

Cust_type
A     25.000000
B    -66.666667
C   -100.000000
D     33.333333

相关问题