python - Average of X*Y items and keeping dimensions of the numpy array -


how take average of example 4 nearby items (2*2) on 2 dimensional array? input is:

[[1,1,1,1],  [1,1,0,0],  [0,0,1,1],  [0,0,0,0]] 

which should result:

[[1, 0.5],  [0, 0.5]] 

numpy.mean(x.reshape(-1, 4), 1) flatten array , average 4 items in wrong order.

additional info

array produced example method:

n = 10 l = 100 = np.zeros((l, l)) points = l*np.random.random((2, n**2)) a[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 = ndimage.gaussian_filter(a, sigma=l/(4.*n)) 

here's 1 way reshaping , summing -

m,n = a.shape a.reshape(m/2,2,n/2,2).sum(axis=(1,3))/4.0 

of course, assumes number of rows , columns divisible 2.

sample run -

in [87]: out[87]:  array([[8, 4, 6, 8, 1, 1],        [6, 7, 8, 5, 3, 4],        [1, 8, 8, 4, 7, 6],        [1, 8, 7, 7, 2, 4]])  in [88]: m,n = a.shape  in [89]: a.reshape(m/2,2,n/2,2).sum(axis=(1,3))/4.0 out[89]:  array([[ 6.25,  6.75,  2.25],        [ 4.5 ,  6.5 ,  4.75]]) 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -