# [Numpy-discussion] subsampling arrays without loops

Jaime Fernández del Río jaime.frio at gmail.com
Thu Oct 3 19:17:31 EDT 2013

```On Thu, Oct 3, 2013 at 4:05 PM, Moroney, Catherine M (398D) <
Catherine.M.Moroney at jpl.nasa.gov> wrote:

> I know I have a lot yet to learn about array striding tricks, so please
> pardon the triviality of this question.
>
> Here is the problem both in words and "dumb" python:
>
> I have a large NxM array that I want to break down into smaller nxn chunks
> where n divides evenly into both N and M.  Then I want to calculate the
> fraction of pixels in each nxn chunk that meets a certain criteria: say (x
> > 1) & (x < 2).
>

If n divides both N and M, you can simply reshape your array to 4D, then
reduce it back to 2D:

import numpy as np

N, M = 1000, 2000
n = 100

a = np.random.rand(N,M) * 5
a_view = a.reshape(a.shape[0] // n, n, a.shape[1] // n, n)
a_fractions = np.sum((a_view > 1) & (a_view < 2), axis=(1, 3)) / (n * n)

>>> a_fractions.shape
(10L, 20L)

>>> a_fractions
array([[ 0.1965,  0.1964,  0.202 ,  0.1997,  0.1976,  0.1997,  0.2026,
0.1951,  0.2051,  0.1995,  0.1926,  0.2006,  0.1973,  0.1964,
0.2046,  0.1977,  0.2066,  0.2009,  0.2003,  0.2013],
...
[ 0.2028,  0.1943,  0.2036,  0.1992,  0.2   ,  0.2009,  0.1971,
0.1996,  0.196 ,  0.196 ,  0.1983,  0.2021,  0.2031,  0.1955,
0.1916,  0.1939,  0.202 ,  0.2064,  0.2021,  0.1954]])

Jaime

--
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus planes
de dominación mundial.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20131003/48ba06ec/attachment.html>
```