numpy.ufunc.reduceat#
method
- 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],则会发生这种情况).- 参数:
- arrayarray_like
要进行操作的数组.
- indicesarray_like
成对的索引,用逗号分隔(不是冒号),指定要归约的切片.
- 轴int, optional
应用 reduceat 的轴.
- dtype数据类型代码,可选
用于执行操作的数据类型. 如果给定了
out,则默认为其数据类型,否则默认为array的数据类型(虽然会对某些情况进行向上转型以保持精度,例如对整数或布尔输入进行numpy.add.reduce).- outndarray, None, or tuple of ndarray and None, optional
用于存储结果的位置.如果未提供或为 None,则返回一个新分配的数组.为了与
ufunc.__call__保持一致,如果作为关键字参数传递,则可以是省略号 (out=...,其效果与 None 相同,因为始终返回一个数组),或者是一个 1 元素元组.
- 返回:
- 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.]])