Find indices of elements equal to zero in a NumPy array

前端 未结 8 1336
孤城傲影
孤城傲影 2020-11-29 17:28

NumPy has the efficient function/method nonzero() to identify the indices of non-zero elements in an ndarray object. What is the most efficient way to obtain th

8条回答
  •  孤城傲影
    2020-11-29 17:36

    You can also use nonzero() by using it on a boolean mask of the condition, because False is also a kind of zero.

    >>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
    
    >>> x==0
    array([False, True, False, True, False, True, False, False, False, False, False], dtype=bool)
    
    >>> numpy.nonzero(x==0)[0]
    array([1, 3, 5])
    

    It's doing exactly the same as mtrw's way, but it is more related to the question ;)

提交回复
热议问题