numpy.ufunc.reduceat#
方法
- ufunc.reduceat(array, indices, axis=0, dtype=None, out=None)#
在单个轴上对指定切片执行(局部)规约。
对于
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],就会发生这种情况)。- 参数:
- arrayarray_like
要进行操作的数组。
- indicesarray_like
成对的索引(用逗号而非冒号分隔),指定要规约(reduce)的切片。
- axisint, optional
执行 reduceat 操作的轴。
- dtype数据类型代码,可选
执行操作所使用的数据类型。如果给定了
out,则默认为out的数据类型;否则默认为array的数据类型(尽管在某些情况下会向上转型以保持精度,例如整数或布尔值输入的numpy.add.reduce)。- outndarray, None, or tuple of ndarray and None, optional
存储结果的位置。如果未提供或为 None,则返回一个新分配的数组。为了与
ufunc.__call__保持一致,如果作为关键字参数传递,它可以是省略号(out=...,其效果与 None 相同,因为总是会返回一个数组),或者是一个单元素元组。
- 返回:
- rndarray
规约后的值。如果提供了 out,则 r 是对 out 的引用。
备注
描述性示例
如果
array是一维的,函数 ufunc.accumulate(array) 等同于ufunc.reduceat(array, indices)[::2],其中indices是range(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.]])