我想根据另一个向量中的分组信息取一个向量的平均值。两个向量的长度相同。我根据每个用户的平均预测创建了下面的最小示例。我如何在 NumPy 中做到这一点?
>>> 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']
最佳答案
“纯 numpy”解决方案可能会使用 np.unique
和 np.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安装后,DataFrame
有 some very nice methods for grouping and summarizing data :
import pandas as pd
df = pd.DataFrame({'name':users, 'pred':pred})
print(df.groupby('name').mean())
# pred
# name
# User0 0.450000
# User1 0.550000
# User2 0.550000
# User3 0.435000
# User4 0.816667
关于python - 使用另一个向量中的分组值进行平均(numpy/Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29243982/