[Numpy-discussion] using the functions nonzero and where

Bill Baxter wbaxter@gmail....
Tue Apr 24 12:24:46 CDT 2007


On 4/21/07, Dennis Cooke <dennis.a.cooke@gmail.com> wrote:
> I'm an ex-Matlab user trying to come up to speed with python and numpy.

Howdy.  First, I hope you've checked out the page:
   http://www.scipy.org/NumPy_for_Matlab_Users

> I'm
> confused on how to use the Numpy functions nonzero() and where().  In
> matlab, the equivalent function (find(a>0) ) would return an array, whereas
> in numpy, where() or nonzero() will return a single element tuple.  For
> example:
>
> In [35]: x = [ 0, 0, 0, 99, 0, 1, 5]
> # and I wish to file the index of the first non-zero element of x - which is
> 3.
>
> In [36]: from numpy import nonzero
> In [37]: i=nonzero(x)
> In [38]: i
> Out[38]: (array([3, 5, 6]),)
> In [39]: i[0]
> Out[39]: array([3, 5, 6])
>
> so nonzero() has output a tuple with a single element = the string
> 'array([3, 5, 6])'

The element is not a string.  It's the array, it shows up like a
string.  (To print things out the method __repr__() is called
automatically and the convention is that that's supposed to return
something which if you typed it in, would evaluate to the same thing.)

> How do I convert this string (or the original tuple)  into an array where
> the first element = 3 (the index of the first non-zero element of my
> original array x).

Just do i[0].  It's an array, not a string.  Try typing "type(i[0])"
and see what it tells you.

--bb


More information about the Numpy-discussion mailing list