[Numpy-discussion] avoiding loops when downsampling arrays

Sturla Molden sturla@molden...
Tue Feb 7 06:57:46 CST 2012


On 06.02.2012 22:27, Sturla Molden wrote:
>
>
>>
>> # Make a 4D view of this data, such that b[i,j]
>> # is a 2D block with shape (4,4) (e.g. b[0,0] is
>> # the same as a[:4, :4]).
>> b = as_strided(a, shape=(a.shape[0]/4, a.shape[1]/4, 4, 4),
>>                 strides=(4*a.strides[0], 4*a.strides[1], a.strides[0], a.strides[1]))
>>
>
> Yes :-) Being used to Fortran (and also MATLAB) this is the kind of mapping It never occurs for me to think about. What else but NumPy is flexible enough to do this? :-)

Actually, using as_strided is not needed. We can just reshape like this:

    (m,n) ---> (m//4, 4, n//4, 4)

and then use np.any along the two length-4 dimensions.

   m,n = data.shape
   cond = lamda x : (x <= t1) & (x >= t2)
   x = cond(data).reshape((m//4, 4, n//4, 4))
   found = np.any(np.any(x, axis=1), axis=2)


Sturla


More information about the NumPy-Discussion mailing list