How do I apply function to third-dimension array effectively with numpy?
<p>I want to apply arbitrary function to 3d-ndarray as element, which use (3rd-dimensional) array for its arguments and return scalar.As a result, we should get 2d-Matrix.</p>

<p>e.g) pseudo code </p>

<pre><code>A = [[[1,2,3],[4,5,6]],
     [[7,8,9],[10,11,12]]]
A.apply_3d_array(sum) ## or apply_3d_array(A,sum) is Okey.
&gt;&gt; [[6,15],[24,33]]
</code></pre>

<p>I understand it's possible with loop using ndarray.shape function,but direct index access is inefficient as official document says. 
Is there more effective way than using loop? </p>

<pre><code>def chromaticity(pixel):
    geo_mean = math.pow(sum(pixel),1/3)
    return map(lambda x: math.log(x/geo_mean),pixel ) 
</code></pre>

<p><code>apply_along_axis</code> is designed to make this task easy:</p>

<pre><code>In [683]: A=np.arange(1,13).reshape(2,2,3)
In [684]: A
Out[684]: 
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])
In [685]: np.apply_along_axis(np.sum, 2, A)
Out[685]: 
array([[ 6, 15],
       [24, 33]])
</code></pre>

<p>It, in effect, does</p>

<pre><code>for all i,j:
    out[i,j] = func( A[i,j,:])
</code></pre>

<p>taking care of the details.  It's not faster than doing that iteration yourself, but it makes it easier.</p>

<p>Another trick is to reshape your input to 2d, perform the simpler 1d iteration, and the reshape the result</p>

<pre><code> A1 = A.reshape(-1, A.shape[-1])
 for i in range(A1.shape[0]):
     out[i] = func(A1[i,:])
 out.reshape(A.shape[:2])
</code></pre>

<p>To do things faster, you need to dig into the guts of the function, and figure out how to use compile numpy operations on more than one dimension.  In the simple case of <code>sum</code>, that function already can work on selected axes.</p>

python arrays numpy multidimensional-array vectorization