numpy.ufunc.accumulate#

method

ufunc.accumulate(array, axis=0, dtype=None, out=None)#

Accumulate the result of applying the operator to all elements.

For a one-dimensional array, accumulate produces results equivalent to:

r = np.empty(len(A))
t = op.identity        # op = the ufunc being applied to A's  elements
for i in range(len(A)):
    t = op(t, A[i])
    r[i] = t
return r

For example, add.accumulate() is equivalent to np.cumsum().

For a multi-dimensional array, accumulate is applied along only one axis (axis zero by default; see Examples below) so repeated use is necessary if one wants to accumulate over multiple axes.

Parameters:
arrayarray_like

The array to act on.

axisint, optional

The axis along which to apply the accumulation; default is zero.

dtypedata-type code, optional

The data-type used to represent the intermediate results. Defaults to the data-type of the output array if such is provided, or the data-type of the input array if no output array is provided.

outndarray, None, or tuple of ndarray and None, optional

Location into which the result is stored. If not provided or None, a freshly-allocated array is returned. For consistency with ufunc.__call__, if passed as a keyword argument, can be Ellipses (out=..., which has the same effect as None as an array is always returned), or a tuple with one entry per output. For a ufunc with a single output, a 1-element tuple is also accepted.

Returns:
rndarray or tuple of ndarray

The accumulated values. If out was supplied, r is a reference to out. For a ufunc with more than one output whose loop implementation registers a reduction loop, r is instead a tuple with one array per output.

Notes

accumulate normally only supports ufuncs with a single output. A ufunc with more than one output can still be used if its loop implementation registers a dedicated reduction loop. Otherwise, calling it raises a TypeError.

Examples

1-D array examples:

>>> import numpy as np
>>> np.add.accumulate([2, 3, 5])
array([ 2,  5, 10])
>>> np.multiply.accumulate([2, 3, 5])
array([ 2,  6, 30])

2-D array examples:

>>> I = np.eye(2)
>>> I
array([[1.,  0.],
       [0.,  1.]])

Accumulate along axis 0 (rows), down columns:

>>> np.add.accumulate(I, 0)
array([[1.,  0.],
       [1.,  1.]])
>>> np.add.accumulate(I) # no axis specified = axis zero
array([[1.,  0.],
       [1.,  1.]])

Accumulate along axis 1 (columns), through rows:

>>> np.add.accumulate(I, 1)
array([[1.,  1.],
       [0.,  1.]])