[Numpy-discussion] shortcut nonzero?

Daniele Nicolodi daniele at grinta.net
Tue Feb 25 14:33:13 EST 2014

> On Tue, Feb 25, 2014 at 2:20 PM, Alan G Isaac <alan.isaac at gmail.com
> <mailto:alan.isaac at gmail.com>> wrote:
>     Is there a shortcut version for finding the first (k) instance(s) of
>     nonzero entries?
>     I'm thinking of Matlab's `find(X,k)`:
>     http://www.mathworks.com/help/matlab/ref/find.html
>     Easy enough to write of course.
>     I thought `flatnonzero` would be the obvious place for this,
>     but it does not have a `first=k` option.
>     Is such an option worth suggesting?

On 25/02/2014 20:28, Yuxiang Wang wrote:> Hi Alan,
> If you are only dealing with 1d array, What about:
> np.nonzero(your_array)[0][:k]

I believe that Alan is looking for a solution that does not need to
iterate all the array to extract only the firs k occurrences.

PS: avoid top posting, please.


More information about the NumPy-Discussion mailing list