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
成对的索引(用逗号分隔,而不是冒号),指定要缩减的切片.
- axis整数,可选
沿其应用 reduceat 的轴.
- dtype数据类型代码,可选
用于执行操作的数据类型.如果给定了
out,则默认为out的数据类型,否则默认为array的数据类型(尽管对于某些情况,会进行向上转换以保持精度,例如整数或布尔输入的numpy.add.reduce).- outndarray, None, or tuple of ndarray and None, optional
结果存储的位置.如果未提供或为 None,则返回新分配的数组.为了与
ufunc.__call__保持一致,如果作为关键字参数传递,则可以是 Ellipses (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.]])