[Numpy-discussion] np.nonzero - order guarantees?

Matthew Brett matthew.brett at gmail.com
Tue Jul 28 12:18:01 EDT 2015


On Tue, Jul 28, 2015 at 4:45 PM, Sebastian Berg
<sebastian at sipsolutions.net> wrote:
> Yes, I think it is guaranteed C order in the results.
>
>
> On Mon Jul 27 14:05:01 2015 GMT+0200, Matthew Brett wrote:
>> Hi,
>>
>> `np.nonzero` for a 2D array `A` returns:
>>
>> row_inds, col_inds = np.nonzero(A)
>>
>> I notice that `row_inds` appears to be sorted by value, and `col_inds`
>> appears to be sorted by value, within each row.
>>
>> Is this a guarantee of the `np.nonzero` function?  If not, does this
>> function guarantee any property of the returned indices, other than
>> the correspondence of the row, column entries?

Joscha Reimer just pointed out that this is not guaranteed for scipy
sparse arrays:

https://github.com/scipy/scipy/pull/4875#discussion_r35528827

>>> A = scipy.sparse.coo_matrix(([2, 1], ([1, 0], [0, 1])))
>>> A.todense()
matrix([[0, 1],
        [2, 0]])
>>> A.nonzero()
(array([1, 0], dtype=int32), array([0, 1], dtype=int32))

This seems rather dangerous - I mean a convention that is nearly
always observed.  I guess at very least we should say what the
guarantee is (or isn't) in the nonzero docstring?

Cheers,

Matthew



More information about the NumPy-Discussion mailing list