Best way to take mean/sum of block matrix in numpy?
<p>I would like to perform some simple calculation on the block matrix (or more generally on the d-dim nd.array). Something like this:</p>

<p><a href="https://i.stack.imgur.com/9SwYH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9SwYH.png" alt="Block matrix"></a></p>

<p>In the picture, capital letters represent a 3 by 3 block matrix, and lower case letters are numbers (mean or sum of block matrices).</p>

<p>Currently, I only know how to do this by using for loop</p>

<pre><code>import numpy as np

test_matrix = np.arange(81).reshape(9,9)
a = np.zeros((3,3))
for i in range(3):
    for j in range(3):
        a[k,i,j] = test_matrix[3*i:3*(i+1),3*j:3*(j+1)].mean()
print a
</code></pre>

<p>But it gets slow if my matrix gets bigger or multi-dimensional, such as the following:</p>

<pre><code>test_matrix = np.arange(81*2).reshape(2,9,9)

a = np.zeros((2,3,3))
for k in range(2):
    for i in range(3):
        for j in range(3):
            a[k,i,j] = test_matrix[k,3*i:3*(i+1),3*j:3*(j+1)].mean()
print a
</code></pre>

<p>Is there any better way to perform this kind of tasks?</p>

<p>Thanks a lot!!</p>