[Numpy-discussion] min depth to nonzero in 3d array

Stephan Hoyer shoyer at gmail.com
Thu Apr 17 13:45:59 EDT 2014


Hi Alan,

You can abuse np.argmax to calculate the first nonzero element in a
vectorized manner:

import numpy as np
A = (2 * np.random.rand(100, 50, 50)).astype(int)

Compare:

np.argmax(A != 0, axis=0)
np.array([[np.flatnonzero(A[:,i,j])[0] for j in range(50)] for i in
range(50)])

You'll also want to check for all zero arrays with np.all:

np.all(A == 0, axis=0)

Cheers,
Stephan


On Thu, Apr 17, 2014 at 9:32 AM, Alan G Isaac <alan.isaac at gmail.com> wrote:

> Given an array A of shape m x n x n
> (i.e., a stack of square matrices),
> I want an n x n array that gives the
> minimum "depth" to a nonzero element.
> E.g., the 0,0 element of the result is
> np.flatnonzero(A[:,0,0])[0]
> Can this be vectorized?
> (Assuming a nonzero element exists is ok,
> but dealing nicely with its absence is even better.)
>
> Thanks,
> Alan Isaac
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20140417/1f269c83/attachment.html>


More information about the NumPy-Discussion mailing list