numpy.ufunc.reduceat#

方法

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

在单个轴上对指定切片执行(局部)reduce 操作。

对于 range(len(indices)) 中的每个 i,reduceat 计算 ufunc.reduce(array[indices[i]:indices[i+1]]),这成为最终结果中平行于 axis 的第 i 个广义“行”(例如,在二维数组中,如果 axis = 0,它成为第 i 行;但如果 axis = 1,它成为第 i 列)。此规则有三个例外:

  • i = len(indices) - 1 时(即最后一个索引),indices[i+1] = array.shape[axis]

  • 如果 indices[i] >= indices[i + 1],则第 i 个广义“行”就是 array[indices[i]]

  • 如果 indices[i] >= len(array)indices[i] < 0,则会引发错误。

输出的形状取决于 indices 的大小,可能比 array 大(如果 len(indices) > array.shape[axis] 就会发生这种情况)。

参数:
array类数组

要操作的数组。

indices类数组

成对的索引,逗号分隔(非冒号),指定要进行 reduce 操作的切片。

axisint, 可选

应用 reduceat 的轴。

dtype数据类型代码, 可选

用于执行操作的数据类型。如果给出 out,则默认为其数据类型;否则默认为 array 的数据类型(但在某些情况下会进行类型提升以保持精度,例如对整数或布尔输入执行 numpy.add.reduce)。

outndarray, None, 或 ndarray 和 None 的元组, 可选

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

返回:
rndarray

归约后的值。如果提供了 outr 是对 out 的引用。

注意

一个描述性示例

如果 array 是一维的,函数 ufunc.accumulate(array) 等同于 ufunc.reduceat(array, indices)[::2],其中 indicesrange(len(array) - 1),并且每隔一个元素放置一个零:indices = zeros(2 * len(array) - 1)indices[1::2] = range(1, len(array))

不要被这个属性的名称迷惑:reduceat(array) 不一定比 array 小。

示例

计算四个连续值的滚动和

>>> import numpy as np
>>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2]
array([ 6, 10, 14, 18])

一个二维示例

>>> x = np.linspace(0, 15, 16).reshape(4,4)
>>> x
array([[ 0.,   1.,   2.,   3.],
       [ 4.,   5.,   6.,   7.],
       [ 8.,   9.,  10.,  11.],
       [12.,  13.,  14.,  15.]])
# reduce such that the result has the following five rows:
# [row1 + row2 + row3]
# [row4]
# [row2]
# [row3]
# [row1 + row2 + row3 + row4]
>>> np.add.reduceat(x, [0, 3, 1, 2, 0])
array([[12.,  15.,  18.,  21.],
       [12.,  13.,  14.,  15.],
       [ 4.,   5.,   6.,   7.],
       [ 8.,   9.,  10.,  11.],
       [24.,  28.,  32.,  36.]])
# reduce such that result has the following two columns:
# [col1 * col2 * col3, col4]
>>> np.multiply.reduceat(x, [0, 3], 1)
array([[   0.,     3.],
       [ 120.,     7.],
       [ 720.,    11.],
       [2184.,    15.]])