ClimateUnboxed
ClimateUnboxed

Reputation: 8087

block mean of 2D numpy array (in both dimensions)

This question is related to Block mean of numpy 2D array (in fact the title is almost the same!) except that my case is a generalization. I want to divide a 2D array into a sub-blocks in both directions and take the mean over the blocks. (The linked example only divides the array in one dimension).

Thus if my array is this:

import numpy as np 
a=np.arange(16).reshape((4,4))

array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

If my sub-blocks have a size 2x2, then my desired answer is

array([[ 2.5,  4.5],
       [10.5, 12.5]])

The only way I could think of doing this was to carefully reshape on one dimension at a time:

np.mean(np.mean(a.reshape((2,2,-1)),axis=1).reshape((-1,2,2)),axis=2)

This gives the correct solution but is a bit of a convoluted mess, and I was wondering if there is a cleaner easier code to do the same thing, maybe some numpy blocking function that I am unaware of ?

Upvotes: 2

Views: 682

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

You can do:

# sample data
a=np.arange(24).reshape((6,4))

rows, cols = a.shape    
a.reshape(rows//2, 2, cols//2, 2).mean(axis=(1,-1))

Output:

array([[ 2.5,  4.5],
       [10.5, 12.5],
       [18.5, 20.5]])

Upvotes: 2

Related Questions