# [Numpy-discussion] avoiding loops when downsampling arrays

Sturla Molden sturla@molden...
Mon Feb 6 15:17:36 CST 2012

```The last t1 on each lineis of course t2. Sorry for the typo. Hard to code on an ipad ;-)

Sturla

Den 6. feb. 2012 kl. 22:12 skrev Sturla Molden <sturla@molden.no>:

>
> Something like this:
>
> m,n = data.shape
> x = data.reshape((m,n//4,4))
> z  = (x[0::4,...] >= t1) & (x[0::4,...] <= t1)
> z |= (x[1::4,...] >= t1) & (x[1::4,...] <= t1)
> z |= (x[2::4,...] >= t1) & (x[2::4,...] <= t1)
> z |= (x[3::4,...] >= t1) & (x[3::4,...] <= t1)
> found = np.any(z, axis=2)
>
> Sturla
>
>
> Den 6. feb. 2012 kl. 21:57 skrev Sturla Molden <sturla@molden.no>:
>
>> Short answer: Create 16 view arrays, each with a stride of 4 in both dimensions. Test them against the conditions and combine the tests with an |= operator. Thus you replace the nested loop with one that has only 16 iterations. Or reshape to 3 dimensions, the last with length 4, and you can do the same with only four view arrays.
>>
>> Sturla
>>
>>
>> Den 6. feb. 2012 kl. 20:16 skrev "Moroney, Catherine M (388D)" <Catherine.M.Moroney@jpl.nasa.gov>:
>>
>>> Hello,
>>>
>>> I have to write a code to downsample an array in a specific way, and I am hoping that
>>> somebody can tell me how to do this without the nested do-loops.  Here is the problem
>>> statement:  Segment a (MXN) array into 4x4 squares and set a flag if any of the pixels
>>> in that 4x4 square meet a certain condition.
>>>
>>> Here is the code that I want to rewrite avoiding loops:
>>>
>>> shape_out = (data_in.shape[0]/4, data_in.shape[1]/4)
>>> found = numpy.zeros(shape_out).astype(numpy.bool)
>>>
>>> for i in xrange(0, shape_out[0]):
>>>  for j in xrange(0, shape_out[1]):
>>>
>>>      excerpt = data_in[i*4:(i+1)*4, j*4:(j+1)*4]
>>>      mask = numpy.where( (excerpt >= t1) & (excerpt <= t2), True, False)
>>>          found[i,j] = True
>>>
>>> Thank you for any hints and education!
>>>
>>> Catherine
>>> _______________________________________________
>>> NumPy-Discussion mailing list
>>> NumPy-Discussion@scipy.org
>>> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>> _______________________________________________
>> NumPy-Discussion mailing list
>> NumPy-Discussion@scipy.org
>> http://mail.scipy.org/mailman/listinfo/numpy-discussion
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
```