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

2014-04-17 Thread Alan G Isaac
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

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

2014-04-17 Thread Stephan Hoyer
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

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

2014-04-17 Thread Eelco Hoogendoorn
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