numpy.ufunc.reduceat#

方法

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 個廣義「列」(例如,在 2 維陣列中,如果 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,選用

要沿其應用 reduceat 的軸。

dtype資料類型代碼,選用

用於執行運算的資料類型。預設為給定 out 的資料類型,否則為 array 的資料類型(但會向上轉換以保留某些情況下的精度,例如整數或布林輸入的 numpy.add.reduce)。

outndarray、None 或 ndarray 和 None 的元組,選用

儲存結果的位置。如果未提供或為 None,則會傳回新分配的陣列。為了與 ufunc.__call__ 一致,如果以關鍵字形式給定,則可以將其包裝在 1 元素元組中。

傳回值:
rndarray

reduce 後的值。如果提供了 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

範例

取得四個連續值的執行總和

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