python - 熊猫:组中的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)
但无法成功。我怎样才能做到这一点?
解决方案
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
推荐阅读
- javascript - 返回一个随机填充字符串变量的数组
- java - java 13中观察者和可观察者的替代方法是什么
- javascript - 在 expressJs 中堆栈 jquery
- javascript - 使用 Selenium Webdriver 和 Java 处理网页对话框窗口上的下拉菜单
- windows - Icecast 服务器 url 仅适用于 ":80"
- javascript - 使用 nodemailer 发送多个单独的电子邮件时出现问题
- c++ - 生成一个 Makefile,使用 Automake 在一个步骤中编译和链接所有源文件
- java - 尝试调用虚拟方法 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)
- r - 无法使用 Rvest 和 Glue 包进行刮擦 bc 表已合并标题 cols 使其不整洁
- html - 图片超链接尺寸错误