Sum slices of consecutive values in a NumPy array

前端 未结 4 1662
甜味超标
甜味超标 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:53

    Here's (yet) another solution:

    In [3]: a.reshape((2,5)).sum(axis=1)
    Out[3]: array([15, 40])
    

    Reshape the one-dimensional array to two rows of 5 columns and sum over the columns:

    In [4]: a.reshape((2,5))
    Out[4]: 
    array([[ 1,  2,  3,  4,  5],
           [ 6,  7,  8,  9, 10]])
    

    The sum along each row (summing the column entries) is specified with axis=1. The reshape happens without copying data (and without modifying the original a) so it is efficient and fast.

提交回复
热议问题