[Numpy-discussion] nonzero() behaviour has changed
Ed Schofield
schofield at ftw.at
Thu May 18 01:56:02 EDT 2006
Alan G Isaac wrote:
> On Tue, 16 May 2006, Alan G Isaac apparently wrote:
>
>> 2. How are people using this? I trust that the numarray
>> behavior was well considered, but I would have expected
>> coordinates to be grouped rather than spread across the
>> arrays in the tuple.
>>
>
> OK, just to satisfy my curiosity:
> does the silence mean that nobody is using
> 'nonzero' in a fashion that leads them to
> prefer the current behavior to the "obvious"
> alternative of grouping the coordinates?
> Is the current behavior just an inherited
> convention, or is it useful in specific applications?
>
I also think a function that groups coordinates would be useful. Here's
a prototype:
def argnonzero(a):
return transpose(a.nonzero())
This has the same effect as:
def argnonzero(a):
nz = a.nonzero()
return array([[nz[i][j] for i in xrange(a.ndim)] for j in
xrange(len(nz[0]))])
The output is always a 2d array, so
>>> a
array([[ 0, 1, 2, 3],
[ 4, 0, 6, 7],
[ 8, 9, 0, 11]])
>>> argnonzero(a)
array([[0, 1],
[0, 2],
[0, 3],
[1, 0],
[1, 2],
[1, 3],
[2, 0],
[2, 1],
[2, 3]])
>>> b = a[0]
>>> argnonzero(b)
array([[1],
[2],
[3]])
>>> c = array([a, a-1, a-2])
>>> argnonzero(c)
array([[0, 0, 1],
[0, 0, 2],
...
It looks a little clumsy for 1d arrays, but I'd argue that, if NumPy
were to offer a function like this, it should always return a 2d array
whose rows are the coordinates for consistency, rather than returning
some squeezed version for indices into 1d arrays.
I'd support the addition of such a function to NumPy. Although it's
tiny, it's not obvious, and it might be useful.
-- Ed
More information about the NumPy-Discussion
mailing list