[Numpy-discussion] using the functions nonzero and where
Tue Apr 24 12:24:46 CDT 2007
On 4/21/07, Dennis Cooke <email@example.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:
> 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
> In : 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
> In : from numpy import nonzero
> In : i=nonzero(x)
> In : i
> Out: (array([3, 5, 6]),)
> In : i
> Out: 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. It's an array, not a string. Try typing "type(i)"
and see what it tells you.
More information about the Numpy-discussion