假设我有一个数组,如下所示:
a = np.array([0, 20, 40, 30, 60, 35, 15, 18, 2])我有一个指数数组,我想要在以下数组之间求平均值:
averaging_indices = np.array([2, 4, 7, 8])我想做的是根据averaging_indices数组对数组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]有没有人能想出一种干净利落的方法呢?我能想到的唯一方法是通过循环,这是非常反numpy的。
发布于 2016-02-15 23:04:13
这是一个使用np.bincount的矢量化方法-
# 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. ])https://stackoverflow.com/questions/35411879
复制相似问题