Max in a sliding window in NumPy array

后端 未结 5 1219
囚心锁ツ
囚心锁ツ 2020-11-30 10:13

I want to create an array which holds all the max()es of a window moving through a given numpy array. I\'m sorry if this sounds confusing. I\'ll give an examp

5条回答
  •  误落风尘
    2020-11-30 11:00

    First of all, I think there is a mistake in your explanation because the 10th element of your initial imput array at the beginning of your explanation is equal to 8, and below, where you apply the window, it is 2.

    After correcting that, I think that the code that does what you want is the following:

    import numpy as np
    a=np.array([ 6,4,8,7,1,4,3,5,7,8,4,6,2,1,3,5,6,3,4,7,1,9,4,3,2 ])
    window=5
    for i in range(0,len(a)-window,1): 
        b[i] = np.amax(a[i:i+window])
    

    I think, this way is better than creating a shifted 2D version of your imput because when you create such a version you need to use much more memory than using the original imput array, so you may run out of memory if the input is large.

提交回复
热议问题