Sum slices of consecutive values in a NumPy array

前端 未结 4 1659
甜味超标
甜味超标 2020-12-19 04:16

Let\'s say I have a numpy array a containing 10 values. Just an example situation here, although I would like to repeat the same for an array with length 100.

4条回答
  •  不思量自难忘°
    2020-12-19 04:57

    One way is to use the add ufunc with its reduceat method:

    >>> np.add.reduceat(a, [0,5])
    array([15, 40])
    

    This sums the slices a[0:5] and a[5:] and returns a new array.

    If you want a Python list, you could call tolist() on the returned array.

    You can use any list of indexes with the method (and they do not have to evenly spaced). For example, if you want slices of 5 each time on an array of length 100:

    >>> b = np.arange(100)
    >>> np.add.reduceat(b, range(0, 100, 5))
    array([ 10,  35,  60,  85, 110, 135, 160, 185, 210, 235, 260, 285, 310,
       335, 360, 385, 410, 435, 460, 485])
    

提交回复
热议问题