Find indices of elements equal to zero in a NumPy array

前端 未结 8 1308
孤城傲影
孤城傲影 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条回答
  •  -上瘾入骨i
    2020-11-29 17:42

    I would do it the following way:

    >>> x = np.array([[1,0,0], [0,2,0], [1,1,0]])
    >>> x
    array([[1, 0, 0],
           [0, 2, 0],
           [1, 1, 0]])
    >>> np.nonzero(x)
    (array([0, 1, 2, 2]), array([0, 1, 0, 1]))
    
    # if you want it in coordinates
    >>> x[np.nonzero(x)]
    array([1, 2, 1, 1])
    >>> np.transpose(np.nonzero(x))
    array([[0, 0],
           [1, 1],
           [2, 0],
           [2, 1])
    

提交回复
热议问题