Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding NumPy's nonzero function

Tags:

numpy

I am trying to understand numpy's nonzero function. The following is an example application:

import numpy arr = numpy.array([[1,0],[1,1]]) arr.nonzero() --> (array([0, 1, 1]), array([0, 0, 1])) 

I can see that because arr is 2-D, the output of nonzero() is a 2-tuple. However, I do not understand why the number of indices in each element of the tuple exceeds the number of rows/columns of the array. I can see that

arr[arr.nonzero()] --> array([1, 1, 1]) 

But how...?

like image 254
hatmatrix Avatar asked Oct 28 '11 00:10

hatmatrix


People also ask

What does Numpy nonzero return?

nonzero. Return the indices of the elements that are non-zero. Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension.

How do you get the first non-zero value in Python?

Use the nonzero() Function to Find the First Index of an Element in a NumPy Array. The nonzero() function returns the indices of all the non-zero elements in a numpy array.

What are non-zero elements?

In mathematics, a non-zero element is any element of an algebraic structure other than the zero element.


1 Answers

Each element of the tuple contains one of the indices for each nonzero value. Therefore, the length of each tuple element is the number of nonzeros in the array.

From your example, the indices of the nonzeros are [0, 0], [1, 0], and [1, 1]. The first element of the tuple is the first index for each of the nonzero values: ([0, 1, 1]), and the second element of the tuple is the second index for each of the nonzero values: ([0, 0, 1]).

Your second code block just returns the nonzero values of the array (I am not clear from the question if the return value is part of the confusion).

>>> arr[arr.nonzero()] array([1, 1, 1]) 

This is more clear if we use an example array with other values.

>>> arr = numpy.array([[1,0],[2,3]]) >>> arr[arr.nonzero()] array([1, 2, 3]) 
like image 93
David Alber Avatar answered Sep 22 '22 02:09

David Alber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!