python - 使用另一个向量中的分组值进行平均(numpy/Python)

标签 python numpy

我想根据另一个向量中的分组信息取一个向量的平均值。两个向量的长度相同。我根据每个用户的平均预测创建了下面的最小示例。我如何在 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.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安装后,DataFramesome 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/

相关文章:

python - 在Python中使用gdal从csv文件生成tiff文件

python - 连接到 SQL Server 会引发 pyodbc.InterfaceError

python - 为什么这个主要测试有效?

python - 从二进制 numpy 矩阵的每一行中随机选择一个?

python - 获取每日最大值会产生奇怪的结果

python - 从列表中删除字符

python - 预期为 ")"皮兰斯

python - 使用Python读取文件夹中的wav文件

python - 数组数组的平均值

python - 如何有效地对向量进行排序以使其与另一个向量的距离最小?