subsampling arrays without loops
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). Here is the "dumb" python code: npix = 4 num_true = numpy.zeros((data.shape[0]/npix, data.shape[1]/npix)) for iline in xrange(0, data.shape[0]/npix): for ismp in xrange(0, data.shape[1]/npix): excerpt = data[iline*npix:(iline+1)*npix, ismp*npix:(ismp+1)*npix] num_true[iline,simp] = numpy.where( (excerpt >= 1) & (excerpt <= 2), True, False).sum() so I'm looping through the number of 4x4 subsets in both dimensions, cutting out a chunk of the data ("excerpt"), and then counting the number of pixels in that excerpt that meet a certain criteria and storing that result for each excerpt. I want to avoid all the loops over iline and ismp. What's the best way of doing this in pure python? I could always write a Fortran/C routine for this task, but I want to learn how best to do it with numpy. Thank you for any advice, Catherine
On Thu, Oct 3, 2013 at 4:05 PM, Moroney, Catherine M (398D) < Catherine.M.Moroney@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.
participants (2)
-
Jaime Fernández del Río -
Moroney, Catherine M (398D)