Pandas : zscore 在组中

Pandas : zscore among the groups

我试图在组中找到值的 z 分数,例如在以下数据中

df:

GROUP VALUE
 1     5
 2     2
 1     10
 2     20
 1     7

第 1 组中有值 5、10、7。所以现在我只在他们的组中寻找他们的 zscore

Sample Desired Output: 

GROUP VALUE Z_SCORE
 1     5     0.5
 2     2     0.01
 1     10    7
 2     20    8.3
 1     7     1.3

上面的 zscore 不是真实的计算值,只是一个表示。

我正在尝试以下方法

def z_score(x):
   z = np.abs(stats.zscore(x))
   return z

df['Z_SCORE'] = df.groupby(['GROUP'])['Value'].apply(z_score)

但未能成功。我怎样才能做到这一点?

使用 GroupBy.transform 而不是 apply 以正确地将 numpy 数组转换为新的 Series 每组:

from  scipy.stats import zscore

def z_score(x):
   z = np.abs(zscore(x))
   return z

df['Z_SCORE'] = df.groupby('GROUP')['VALUE'].transform(z_score)

print (df)
   GROUP  VALUE   Z_SCORE
0      1      5  1.135550
1      2      2  1.000000
2      1     10  1.297771
3      2     20  1.000000
4      1      7  0.162221

使用 GroupBy.apply 的解决方案是可能的,但对于 return Series 和每个组的索引是必要的更改功能:

def z_score(x):
   z = np.abs(zscore(x))
   return pd.Series(z, index=x.index)


df['Z_SCORE'] = df.groupby('GROUP')['VALUE'].apply(z_score)
print (df)
   GROUP  VALUE   Z_SCORE
0      1      5  1.135550
1      2      2  1.000000
2      1     10  1.297771
3      2     20  1.000000
4      1      7  0.162221