Python Running cumulative sum with a given window

前端 未结 4 860
离开以前
离开以前 2020-12-10 19:09

What I want to do is generate a numpy array that is the cumulative sum of another numpy array given a certain window.

For example, given an array [1,2,3,4,5,6

4条回答
  •  离开以前
    2020-12-10 19:29

    seberg's answer is better and more general than mine, but note that you need to zero-pad your samples to get the result you want.

    import numpy as np
    from numpy.lib.stride_tricks import as_strided as ast
    samples = 100
    window = 3
    padding = np.zeros(window - 1)
    # zero-pad your samples
    a = np.concatenate([padding,np.arange(1,samples + 1)])
    newshape = (len(a) - window,window)
    newstrides = a.strides * 2
    # this gets you a sliding window of size 3, with a step of 1
    strided = ast(a,shape = newshape,strides = newstrides)
    # get your moving sum
    strided.sum(1)
    

提交回复
热议问题