Python vectorizing nested for loops
<p>I'd appreciate some help in finding and understanding a pythonic way to optimize the following array manipulations in nested for loops:</p>

<pre><code>def _func(a, b, radius):
    "Return 0 if a&gt;b, otherwise return 1"
    if distance.euclidean(a, b) &lt; radius:
        return 1
    else:
        return 0

def _make_mask(volume, roi, radius):
    mask = numpy.zeros(volume.shape)
    for x in range(volume.shape[0]):
        for y in range(volume.shape[1]):
            for z in range(volume.shape[2]):
                mask[x, y, z] = _func((x, y, z), roi, radius)
    return mask
</code></pre>

<p>Where <code>volume.shape</code> (182, 218, 200) and <code>roi.shape</code> (3,) are both <code>ndarray</code> types; and <code>radius</code> is an <code>int</code> </p>

<p>Say you first build an <code>xyzy</code> array:</p>

<pre><code>import itertools

xyz = [np.array(p) for p in itertools.product(range(volume.shape[0]), range(volume.shape[1]), range(volume.shape[2]))]
</code></pre>

<p>Now, using <a href="http://docs.scipy.org/doc/numpy-1.10.4/reference/generated/numpy.linalg.norm.html"><code>numpy.linalg.norm</code></a>, </p>

<pre><code>np.linalg.norm(xyz - roi, axis=1) &lt; radius
</code></pre>

<p>checks whether the distance for each tuple from <code>roi</code> is smaller than radius.</p>

<p>Finally, just <code>reshape</code> the result to the dimensions you need.</p>

python numpy vectorization