numpy.ufunc.reduceat

方法

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

在单个轴上使用指定切片执行(本地)缩减。

因为我在 range(len(indices))reduceat 计算 ufunc.reduce(array[indices[i]:indices[i+1]]) ,它成为第i个广义“行”,与 axis 在最终结果中(例如,在二维数组中,如果 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可选的

应用减速器的轴。

dtype数据类型代码,可选

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

outndarray、none或ndarray和none的元组,可选

存储结果的位置。如果未提供或没有,则返回新分配的数组。为了与 ufunc.__call__ ,如果作为关键字提供,则可以将其包装在一个1元素元组中。

在 1.13.0 版更改: 关键字参数允许使用元组。

返回
r恩达雷

减少的值。如果 out 供应, r 是指 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 .

实例

取四个连续值的连续和:

>>> 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.]])