numpy.ufunc.reduceat#

method

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

Performs a (local) reduce with specified slices over a single axis.

For i inrange(len(indices)),reduceat computesufunc.reduce(array[indices[i]:indices[i+1]]), which becomes the i-thgeneralized “row” parallel toaxis in the final result (i.e., in a2-D array, for example, ifaxis = 0, it becomes the i-th row, but ifaxis = 1, it becomes the i-th column). There are three exceptions to this:

  • wheni=len(indices)-1 (so for the last index),indices[i+1]=array.shape[axis].

  • ifindices[i]>=indices[i+1], the i-th generalized “row” issimplyarray[indices[i]].

  • ifindices[i]>=len(array) orindices[i]<0, an error is raised.

The shape of the output depends on the size ofindices, and may belarger thanarray (this happens iflen(indices)>array.shape[axis]).

Parameters:
arrayarray_like

The array to act on.

indicesarray_like

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

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 ofout if given, and the data type ofarray otherwise (thoughupcast to conserve precision for some cases, such asnumpy.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 withufunc.__call__, if passed as a keywordargument, can be Ellipses (out=..., which has the same effectas None as an array is always returned), or a 1-element tuple.

Returns:
rndarray

The reduced values. Ifout was supplied,r is a reference toout.

Notes

A descriptive example:

Ifarray is 1-D, the functionufunc.accumulate(array) is the same asufunc.reduceat(array,indices)[::2] whereindices isrange(len(array)-1) with a zero placedin 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 notnecessarily smaller thanarray.

Examples

To take the running sum of four successive values:

>>>importnumpyasnp>>>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)>>>xarray([[ 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.]])
On this page