根据另一个索引数组求一个数组的平均值

2024-09-25 00:32:57 发布

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

假设我有这样一个数组:

a = np.array([0, 20, 40, 30, 60, 35, 15, 18, 2])

我有一个指数数组,我想平均:

averaging_indices = np.array([2, 4, 7, 8])

我要做的是根据数组的平均值来平均数组a的元素。为了说明这一点,我想取平均值:

np.mean(a[0:2]), np.mean(a[2:4]), np.mean(a[4:7]), np.mean(a[7,8]), np.mean(a[8:])

在本例中,我想返回一个具有正确维数的数组

result = [10, 35, 36.66, 18, 2]

有人能想出一个巧妙的方法吗?我能想象的唯一方法就是循环,这是非常反努比的。你知道吗


Tags: 方法元素np数组result指数meanarray
1条回答
网友
1楼 · 发布于 2024-09-25 00:32:57

这里有一个向量化的方法^{}-

# Create "shifts array" and then IDs array for use with np.bincount later on
shifts_array = np.zeros(a.size,dtype=int)
shifts_array[averaging_indices] = 1
IDs = shifts_array.cumsum()

# Use np.bincount to get the summations for each tag and also tag counts.
# Thus, get tagged averages as final output.
out = np.bincount(IDs,a)/np.bincount(IDs)

样本输入,输出-

In [60]: a
Out[60]: array([ 0, 20, 40, 30, 60, 35, 15, 18,  2])

In [61]: averaging_indices
Out[61]: array([2, 4, 7, 8])

In [62]: out
Out[62]: array([ 10.        ,  35.        ,  36.66666667,  18.        ,   2.        ])

相关问题 更多 >