如何在numpy数组中获取每对值的均值?

时间:2017-11-15 19:13:57

标签: python numpy scipy

我要做的是通过找到每个不同元素对的平均值并将值设置为平均值来降低1D数据的“分辨率”。例如:

[ 1, 2, 3, 4 ]

应该成为:

[ 1.5, 1.5, 3.5, 3.5 ]

如果元素的数量是奇数,则最后一个保持不变,或者被删除/忽略。有一个简单的方法吗?

也许首先获得[ 1.5, 3.5 ]然后复制每个元素会更容易 - 我不确定。

最终我想继续这样做(或者每一对迭代,然后每四个,然后每八个,然后每2 ^ i),这样分辨率会变得越来越低,直到它只是一个大的意思。

1 个答案:

答案 0 :(得分:2)

您可以使用像

这样的重塑形式
a = np.arange(1,15)
# groups of four in this example
k = 4 
result = np.empty(a.shape)
# arrange the elements in as many full (4 item) rows as possible
rect = k * (len(a) // k)
resview = np.reshape(result[:rect], (-1, k))
# perform mean along rows without collapsing them
resview[...] = np.mean(np.reshape(a[:rect], (-1, k)), axis=-1, keepdims=True)
if len(a) > rect:
    # handle the last, incomplete (<4 items) row
    result[rect:] = a[rect:].mean()
print(result)
[  2.5   2.5   2.5   2.5   6.5   6.5   6.5   6.5  10.5  10.5  10.5  10.5  13.5  13.5]