Python Running cumulative sum with a given window

前端 未结 4 864
离开以前
离开以前 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:35

    You should likely use numpy, unless you really don't care about speed (though I would prefere it anyways). So you could use convolve or stride_tricks based approaches (these are not obvious, but solve these things nicely).

    For example given a function like this (you can find more and fancier versions too):

    def embed(array, dim, lag=1):
        """Create an embedding of array given a resulting dimension and lag.
        The array will be raveled before embedding.
        """
        array = np.asarray(array)
        array = array.ravel()
        new = np.lib.stride_tricks.as_strided(array,
                                         (len(array)-dim*lag+lag, dim),
                                         (array.strides[0], array.strides[0]*lag))
        return new
    

    You can do:

    embedded = embed(array, 400)
    result = embedded.sum(1)
    

    Which is memory efficient (the embedding or whatever you call it, does only create a view) and fast. The other approach of course would be to use convolve:

    np.convolve(array, np.ones(400), mode='valid')
    

    I don't know if you want the non full windows too, this would be the same as using mode='full' (default) for the convolve. For the other approach, that would have to be handled some other way.

提交回复
热议问题