numpy.ufunc.accumulate#

method

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

将运算符应用于所有元素后累积结果.

对于一维数组,accumulate 产生的结果等效于:

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

例如,add.accumulate() 等同于 np.cumsum().

对于多维数组,accumulate 仅沿一个轴应用(默认轴为零;请参见下面的示例),因此如果要累积多个轴,则需要重复使用.

参数:
arrayarray_like

要操作的数组.

axis整数,可选

应用累积的轴;默认为零.

dtype数据类型代码,可选

用于表示中间结果的数据类型.如果提供了输出数组,则默认为输出数组的数据类型;如果未提供输出数组,则默认为输入数组的数据类型.

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

结果存储的位置.如果未提供或为 None,则返回新分配的数组.为了与 ufunc.__call__ 保持一致,如果作为关键字参数传递,则可以是 Ellipses ( out=... ,其效果与 None 相同,因为始终返回一个数组),或者是一个 1 元素元组.

返回:
rndarray

累积值.如果提供了 out ,则 r 是对 out 的引用.

示例

一维数组示例:

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

二维数组示例:

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

沿轴 0(行)累积,向下到列:

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

沿轴 1(列)累积,通过行:

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