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` 方向的第 i 個廣義“行”(例如,在二維數組中, axis = i1 行列)。但有三個例外:

  • 當「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

The array to act on.

indicesarray_like

Paired indices, comma separated (not colon), specifying slices to reduce.

axisint, optional

The axis along which to apply the reduceat.

dtypedata-type code, optional

The data type used to perform the operation. Defaults to that of out if given, and the data type of array otherwise (though upcast to conserve precision for some cases, such as numpy.add.reduce for integer or boolean input).

outndarray, None, or tuple of ndarray and None, optional

Location into which the result is stored. If not provided or None, a freshly-allocated array is returned. For consistency with ufunc.__call__, if passed as a keyword argument, can be Ellipses (out=..., which has the same effect as None as an array is always returned), or a 1-element tuple.

回傳值:
rndarray

The reduced values. If out was supplied, r is a reference to out.

Notes

A descriptive example:

If array is 1-D, the function ufunc.accumulate(array) is the same as ufunc.reduceat(array, indices)[::2] where indices is range(len(array) - 1) with a zero placed in every other element: indices = zeros(2 * len(array) - 1), indices[1::2] = range(1, len(array)).

Don’t be fooled by this attribute’s name: reduceat(array) is not necessarily smaller than array.

範例

To take the running sum of four successive values:

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

A 2-D example:

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