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...?
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.
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.
In mathematics, a non-zero element is any element of an algebraic structure other than the zero element.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With