numpy.ufunc.reduceat¶
-
ufunc.
reduceat
(a, indices, axis=0, dtype=None, out=None)¶ 使用单个轴上的指定切片执行(局部)缩减。
For i in
range(len(indices))
,reduceat
computesufunc.reduce(a[indices[i]:indices[i+1]])
, which becomes the i-th generalized “row” parallel to axis in the final result (i.e., in a 2-D array, for example, if axis = 0, it becomes the i-th row, but if axis = 1, it becomes the i-th column). 这里有三个例外:- when
i = len(indices) - 1
(so for the last index),indices[i+1] = a.shape[axis]
. - 如果
索引[i] = 索引[i + t5>
,第i个广义“行”仅仅是a[indices[i]]
。 - 如果
索引[i] > = len(a)
或] < 0
时,会出现错误。
输出的形状取决于
indices
的大小,并且可能大于a(如果len(indices) > a.shape [axis]
)。参数: a:array_like
要执行的数组。
indices:array_like
成对索引,逗号分隔(不是冒号),指定要减少的切片。
axis:int,可选
沿着哪条轴应用缩小。
dtype:数据类型代码,可选
用于表示中间结果的类型。默认为输出数组(如果提供)的数据类型,或输入数组(如果未提供输出数组)的数据类型。
out:ndarray,可选
存储结果的位置。如果未提供,则返回新分配的数组。
返回: r:ndarray
减小的值。如果提供out,则r是对out的引用。
笔记
一个描述性示例:
If a is 1-D, the function ufunc.accumulate(a) is the same as
ufunc.reduceat(a, indices)[::2]
whereindices
isrange(len(array) - 1)
with a zero placed in every other element:indices = zeros(2 * len(a) - 1)
,indices[1::2] = range(1, len(a))
.不要被此属性的名称欺骗:reduceat(a)不一定小于a。
例子
要获取四个连续值的运行总和:
>>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2] array([ 6, 10, 14, 18])
2-D示例:
>>> 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.]])
- when