Understanding NumPy's nonzero function

后端 未结 1 1501
醉话见心
醉话见心 2021-01-31 03:25

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.nonz         


        
相关标签:
1条回答
  • 2021-01-31 04:01

    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])
    
    0 讨论(0)
提交回复
热议问题