查找(并记录)numpy数组的切片的最大值

时间:2018-07-10 19:40:53

标签: python arrays numpy max

给定一个a = [0, 3, 2, 4, 0, 2, 3, 1, 1, 6, 2]这样的numpy数组,是否有一种简单的方法来记录每3个值的最大值?数组的长度不能为3的倍数。在这种情况下,结果应为b = [3, 4, 3, 6]

我想到了一些类似的东西

b = [max(a[k:k+3]) for k in range(0, len(a), 3)

,但是它没有考虑3的最后一个倍数之后的值(应该是)。

我还考虑过重新排列numpy数组,使其具有3 * n行,并使用numpy模块沿正确的轴获取最大值,但同样,我不确定如何处理这些值在3的最后一个倍数之后。

3 个答案:

答案 0 :(得分:3)

方法1

我们可以使用np.ufunc.reduceat来执行这样的分组/间隔归约运算。因此,要获得每个间隔内的running build_exe值,我们将有-

maximum

样品运行-

W = 3 # group width
np.maximum.reduceat(a,np.r_[:len(a):W])

方法2

这里还有In [166]: a Out[166]: array([0, 3, 2, 4, 0, 2, 3, 1, 1, 6, 2]) In [167]: W = 3 In [168]: np.maximum.reduceat(a,np.r_[:len(a):W]) Out[168]: array([3, 4, 3, 6]) -

slicing

样品运行-

def max_interval_slice(a, W=3):
    n = len(a)//W
    max0 = a[:n*W].reshape(-1,W).max(1)
    if n*W==len(a):
        return max0
    else:
        return np.r_[max0, np.max(a[n*W:])]

答案 1 :(得分:2)

首次使用 np.pad

a = np.pad(a, [0, 1], mode='constant')

然后 reshape max

>>> np.max(a.reshape(-1, 3), axis=1)
array([3, 4, 3, 6])

要对此进行概括,只需计算填充以将其重塑为所需的尺寸即可。

答案 2 :(得分:2)

要最大程度地减少所需的重新分配量,您可以计算出所有元素的最大值,这些元素适合3的倍数,然后计算其余部分的最大值。此解决方案不是那么简单,但是不会创建不必要的数据副本:

n = 3  # The group width
prefix, suffix = divmod(a.size, n)
output = np.empty(prefix + bool(suffix))
a[:n * prefix].reshape(-1, n).max(axis=1, out=output[:prefix])
if suffix:
    output[-1] = a[-suffix:].max()