Numpy blockwise reduce operations Numpy blockwise reduce operations numpy numpy

Numpy blockwise reduce operations


Have you looked at ufunc.reduceat? With np.maximum, you can do something like:

>>> np.maximum.reduceat(x, indices)

which yields the maximum values along the slices x[indices[i]:indices[i+1]]. To get what you want (x[indices[2i]:indices[2i+1]), you could do

>>> np.maximum.reduceat(x, indices)[::2]

if you don't mind the extra computations of x[inidices[2i-1]:indices[2i]]. This yields the following:

>>> numpy.array([numpy.max(x[ib:ie]) for ib,ie in zip(istart,iend)])array([ 0.60265618,  0.97866485,  0.78869449,  0.79371198,  0.15463711,        0.72413702,  0.97669218,  0.86605981])>>> np.maximum.reduceat(x, indices)[::2]array([ 0.60265618,  0.97866485,  0.78869449,  0.79371198,  0.15463711,        0.72413702,  0.97669218,  0.86605981])


you can use numpy.r_
like this:

what_i_want = np.array([np.max(x[np.r_[ib:ie]]) for ib,ie in zip(istart,iend)])


(A non-numpy solution, using astropy)

import numpy as npfrom astropy.nddata.utils import block_reducedata = np.arange(16).reshape(4, 4)block_reduce(data, 2)    

will convert:

array([[ 0,  1,  2,  3],       [ 4,  5,  6,  7],       [ 8,  9, 10, 11],       [12, 13, 14, 15]])

to:

array([[10, 18],       [42, 50]])

See this for more examples.