Creating a tumbling windows in python

后端 未结 3 1111
离开以前
离开以前 2021-01-27 20:45

Just wondering if there is a way to construct a tumbling window in python. So for example if I have list/ndarray , listA = [3,2,5,9,4,6,3,8,7,9]. Then how could I f

3条回答
  •  猫巷女王i
    2021-01-27 21:12

    Using numpy, you can extend the list with zeroes so its length is divisible by the window size, and reshape and compute the maxalong the second axis:

    def moving_maxima(a, w):
        mod = len(a)%w
        d = w if mod else mod
        x = np.r_[a, [0]*(d-mod)]
        return x.reshape(-1,w).max(1)
    

    Some examples:

    moving_maxima(listA,2)
    # array([3., 9., 6., 8., 9.])
    
    moving_maxima(listA,3)
    #array([5, 9, 8, 9])
    
    moving_maxima(listA,4)
    #array([9, 8, 9])
    

提交回复
热议问题