首页 > 解决方案 > 熊猫:组中的zscore

问题描述

我正在尝试在组中找到 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)

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

标签: pythonpandasgroup-byquartile

解决方案


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

with 的解决方案是可能的,但对于每个组的索引GroupBy.apply返回是必要的更改函数: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

推荐阅读