[Numpy-discussion] min depth to nonzero in 3d array
Eelco Hoogendoorn
hoogendoorn.eelco at gmail.com
Thu Apr 17 13:49:13 EDT 2014
I agree; argmax would the best option here; though I would hardly call it
abuse. It seems perfectly readable and idiomatic to me. Though the !=
comparison requires an extra pass over the array, that's the kind of
tradeoff you make in using numpy.
On Thu, Apr 17, 2014 at 7:45 PM, Stephan Hoyer <shoyer at gmail.com> wrote:
> 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
>>
>
>
> _______________________________________________
> 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/5845b245/attachment.html>
More information about the NumPy-Discussion
mailing list