NumPy具有有效的函数/方法nonzero()来识别ndarray对象中非零元素的索引.什么是最有效的方式来获得该元素的索引做具有零值?
mtr*_*trw 197
numpy.where()是我的最爱.
>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.where(x == 0)[0]
array([1, 3, 5])
Run Code Online (Sandbox Code Playgroud)
MSe*_*ert 25
import numpy as np
arr = np.array([[1,2,3], [0, 1, 0], [7, 0, 2]])
np.argwhere(arr == 0)
Run Code Online (Sandbox Code Playgroud)
它将所有找到的索引作为行返回:
array([[1, 0], # Indices of the first zero
[1, 2], # Indices of the second zero
[2, 1]], # Indices of the third zero
dtype=int64)
Run Code Online (Sandbox Code Playgroud)
nat*_*e c 23
您可以搜索任何标量条件:
>>> a = np.asarray([0,1,2,3,4])
>>> a == 0 # or whatver
array([ True, False, False, False, False], dtype=bool)
Run Code Online (Sandbox Code Playgroud)
这会将数组作为条件的布尔掩码返回.
小智 12
你也可以nonzero()在条件的布尔掩码上使用它,因为False它也是一种零.
>>> 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])
Run Code Online (Sandbox Code Playgroud)
它的方式完全一样mtrw,但它与问题更相关;)
如果您正在使用一维数组,则有一个语法糖:
>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.flatnonzero(x == 0)
array([1, 3, 5])
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以使用 numpy.nonzero 来查找零。
>>> import numpy as np
>>> x = np.array([1,0,2,0,3,0,0,4,0,5,0,6]).reshape(4, 3)
>>> np.nonzero(x==0) # this is what you want
(array([0, 1, 1, 2, 2, 3]), array([1, 0, 2, 0, 2, 1]))
>>> np.nonzero(x)
(array([0, 0, 1, 2, 3, 3]), array([0, 2, 1, 1, 0, 2]))
Run Code Online (Sandbox Code Playgroud)