使用另一个数组中的特定值计算数组的平均值

时间:2016-09-20 15:39:59

标签: python arrays performance numpy

我有这些numpy数组:

array1 = np.array([-1, -1, 1, 1, 2, 1, 2, 2])
array2 = np.array([34.2, 11.2, 22.1, 78.2, 55.0, 66.87, 33.3, 11.56])

现在我想返回一个2d数组,其中有来自array1的每个独特值的均值,所以我的输出看起来像这样:

array([[-1, 22.7],
       [ 1, 55.7],
       [ 2, 33.3]])

是否有一种有效的方法可以将这些1D数组连接到一个2D数组?谢谢!

2 个答案:

答案 0 :(得分:1)

以下是使用np.uniquenp.bincount -

的方法
# Get unique array1 elems, tag them starting from 0 and get their tag counts
unq,ids,count = np.unique(array1,return_inverse=True,return_counts=True)

# Use the tags/IDs to perform ID based summation of array2 elems and 
# thus divide by the ID counts to get ID based average values
out = np.column_stack((unq,np.bincount(ids,array2)/count))

示例运行 -

In [16]: array1 = np.array([-1, -1, 1, 1, 2, 1, 2, 2])
    ...: array2 = np.array([34.2, 11.2, 22.1, 78.2, 55.0, 66.87, 33.3, 11.56])
    ...: 

In [18]: out
Out[18]: 
array([[ -1.        ,  22.7       ],
       [  1.        ,  55.72333333],
       [  2.        ,  33.28666667]])

答案 1 :(得分:1)

这是一个典型的分组操作,numpy_indexed包(免责声明:我是它的作者)为numpy提供了扩展,可以高效,简洁地执行这些类型的操作:

import numpy_indexed as npi
groups, means = npi.group_by(array_1).mean(array_2)

请注意,您也可以通过这种方式轻松执行其他类型的缩减,例如中位数。

相关问题