np.add.reduceat()
Parameters ---------- a : array_like The array to act on. indices : array_like Paired indices, comma separated (not colon), specifying slices to reduce. axis : int, optional The axis along which to apply the reduceat. dtype : data-type code, optional The type used to represent the intermediate results. Defaults to the data type of the output array if this is provided, or the data type of the input array if no output array is provided. out : ndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If not provided or None, a freshly-allocated array is returned. For consistency with ``ufunc.__call__``, if given as a keyword, this may be wrapped in a 1-element tuple. .. versionchanged:: 1.13.0 Tuples are allowed for keyword argument. Returns ------- r : ndarray The reduced values. If `out` was supplied, `r` is a reference to `out`.
np.add.reduceat()的使用
demo = np.add.reduceat(np.arange(8),[0, 4, 1, 5, 2, 6, 3, 7])[::2]
上例即:demo = np.add.redrceat([0, 1, 2, 3, 4, 5, 6, 7], [0, 4, 1, 5, 2, 6, 3, 7])[::2]
令a = [0, 1, 2, 3, 4, 5, 6, 7], b = [0, 4, 1, 5, 2, 6, 3, 7]
计算过程如下:
b[i+1] > b[i], demo[i] = np.reduce(add, a[b[i]] : a[b[i+1]]),如:4 > 0, demo[0] = 0 + 1 + 2 + 3
b[i+1] < b[i], demo[i] = np.reduce(add, a[b[i]]),如:1 < 4, demo[1] = 4
结果如下:
>> demo = np.add.redrceat([0, 1, 2, 3, 4, 5, 6, 7], [0, 4, 1, 5, 2, 6, 3, 7])
>> print(demo)
[ 6 4 10 5 14 6 18 7]
>> demo_ = np.add.redrceat([0, 1, 2, 3, 4, 5, 6, 7], [0, 4, 1, 5, 2, 6, 3, 7])[::2]
>> print(demo_)
[ 6 10 14 18]
#[::2] => list[start:end:step]