# [Numpy-discussion] subsampling array without loops

Stéfan van der Walt stefan@sun.ac...
Thu Aug 28 01:02:27 CDT 2008

```2008/8/26 Anne Archibald <peridot.faceted@gmail.com>:
> 2008/8/22 Catherine Moroney <Catherine.M.Moroney@jpl.nasa.gov>:
>> I'm looking for a way to acccomplish the following task without lots
>> of loops involved, which are really slowing down my code.
>>
>> I have a 128x512 array which I want to break down into 2x2 squares.
>> Then, for each 2x2 square I want to do some simple calculations
>> such as finding the maximum value, which I then store in a 64x256
>> array.
>
> You should be able to do some of this with reshape and transpose:
> In [1]: import numpy as np
>
> In [3]: A = np.zeros((128,512))
>
> In [4]: B = np.reshape(A,(64,2,256,2))
>
> In [5]: C = np.transpose(B,(0,2,1,3))
>
> In [6]: C.shape
> Out[6]: (64, 256, 2, 2)

Or you can obtain a similar effect using my new favorite hammer:

from numpy.lib import stride_tricks

rows, cols = x.shape
el = x.dtype.itemsize
y = stride_tricks.as_strided(x, shape=(rows/2, cols/2, 2, 2),
strides=(el*2*cols, el*2, el*cols, el))

Cheers
Stéfan
```