在另一个向量中使用分组值求平均值(numpy/Python)

2024-04-25 23:58:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想取一个向量的平均值,基于另一个向量的分组信息。这两个向量的长度相同。我在下面创建了一个基于每个用户平均预测的最小示例。我在纽比怎么做?在

       >>> pred
           [ 0.99  0.23  0.11  0.64  0.45  0.55 0.76  0.72  0.97 ] 
       >>> users
           ['User2' 'User3' 'User2' 'User3' 'User0' 'User1' 'User4' 'User4' 'User4']

Tags: 用户信息示例向量users平均值user1pred
3条回答

如果您想坚持使用numpy,最简单的方法是使用^{}和{a2}:

>>> pred = np.array([0.99, 0.23, 0.11, 0.64, 0.45, 0.55, 0.76, 0.72, 0.97])
>>> users = np.array(['User2', 'User3', 'User2', 'User3', 'User0', 'User1',
...                   'User4', 'User4', 'User4'])
>>> unq, idx, cnt = np.unique(users, return_inverse=True, return_counts=True)
>>> avg = np.bincount(idx, weights=pred) / cnt
>>> unq
array(['User0', 'User1', 'User2', 'User3', 'User4'],
      dtype='|S5')
>>> avg
array([ 0.45      ,  0.55      ,  0.55      ,  0.435     ,  0.81666667])

一个紧凑的解决方案是使用numpy_indexed(否认:我是它的作者),它实现了一个类似于Jaime提出的矢量化解决方案;但是它具有更干净的界面和更多的测试:

import numpy_indexed as npi
npi.group_by(users).mean(pred)

“纯numpy”解决方案可能使用np.uniquenp.bincount的组合:

import numpy as np

pred = [0.99,  0.23,  0.11,  0.64,  0.45,  0.55, 0.76,  0.72,  0.97]
users = ['User2', 'User3', 'User2', 'User3', 'User0', 'User1', 'User4',
         'User4', 'User4']

# assign integer indices to each unique user name, and get the total
# number of occurrences for each name
unames, idx, counts = np.unique(users, return_inverse=True, return_counts=True)

# now sum the values of pred corresponding to each index value
sum_pred = np.bincount(idx, weights=pred)

# finally, divide by the number of occurrences for each user name
mean_pred = sum_pred / counts

print(unames)
# ['User0' 'User1' 'User2' 'User3' 'User4']

print(mean_pred)
# [ 0.45        0.55        0.55        0.435       0.81666667]

如果安装了pandas,则DataFrames有{a2}:

^{pr2}$

相关问题 更多 >