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.is...@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@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
_______________________________________________
NumPy-Discussion mailing list
NumPy-Discussion@scipy.org
http://mail.scipy.org/mailman/listinfo/numpy-discussion

Reply via email to