Max in a sliding window in NumPy array

后端 未结 5 1208
囚心锁ツ
囚心锁ツ 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 10:56

    Approach #1 : You could use 1D max filter from Scipy -

    from scipy.ndimage.filters import maximum_filter1d
    
    def max_filter1d_valid(a, W):
        hW = (W-1)//2 # Half window size
        return maximum_filter1d(a,size=W)[hW:-hW]
    

    Approach #2 : Here's another approach with strides : strided_app to create a 2D shifted version as view into the array pretty efficiently and that should let us use any custom reduction operation along the second axis afterwards -

    def max_filter1d_valid_strided(a, W):
        return strided_app(a, W, S=1).max(axis=1)
    

    Runtime test -

    In [55]: a = np.random.randint(0,10,(10000))
    
    # @Abdou's solution using pandas rolling
    In [56]: %timeit pd.Series(a).rolling(5).max().dropna().tolist()
    1000 loops, best of 3: 999 µs per loop
    
    In [57]: %timeit max_filter1d_valid(a, W=5)
        ...: %timeit max_filter1d_valid_strided(a, W=5)
        ...: 
    10000 loops, best of 3: 90.5 µs per loop
    10000 loops, best of 3: 87.9 µs per loop
    

提交回复
热议问题