Python 在NumPy数组中查找等于零的元素索引
NumPy具有识别Python 在NumPy数组中查找等于零的元素索引,python,numpy,Python,Numpy,NumPy具有识别ndarray对象中非零元素索引的有效功能/方法。获取值为零的元素索引的最有效方法是什么?是我最喜欢的方法 >>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8]) >>> numpy.where(x == 0)[0] array([1, 3, 5]) 您可以使用以下命令搜索任何标量条件: >>> a = np.asarray([0,1,2,3,4]) >>> a == 0
ndarray
对象中非零元素索引的有效功能/方法。获取值为零的元素索引的最有效方法是什么?是我最喜欢的方法
>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.where(x == 0)[0]
array([1, 3, 5])
您可以使用以下命令搜索任何标量条件:
>>> a = np.asarray([0,1,2,3,4])
>>> a == 0 # or whatver
array([ True, False, False, False, False], dtype=bool)
这将返回作为条件布尔掩码的数组。如果使用一维数组,则有一个语法糖:
>x=numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>>numpy.flatnonzero(x==0)
数组([1,3,5])
您还可以在条件的布尔掩码上使用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])
它的做法与mtrw的做法完全相同,但与问题更相关;) 有
它将所有找到的索引作为行返回:
array([[1, 0], # Indices of the first zero
[1, 2], # Indices of the second zero
[2, 1]], # Indices of the third zero
dtype=int64)
我会这样做:
>>> 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])
可以使用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]))
我正在努力记住Python。为什么
where()
返回元组numpy。其中(x==0)[1]
超出范围。那么索引数组耦合到什么呢?@Zhubarb-索引的大多数用法都是元组-np.zero((3,)
,例如,生成一个3长的向量。我怀疑这是为了使解析参数变得容易。否则,像np.zero(3,0,dtype='int16')
与np.zero(3,3,3,dtype='int16')
之类的东西将很难实现。否其中
返回ndarray
s的元组,每个元组对应于输入的维度。在这种情况下,输入是一个数组,因此输出是一个1元组。如果x是一个矩阵,那么它将是一个2元组
,因此在numpy 1.16中,特别建议直接使用numpy.nonzero
,而不是只使用一个参数调用where
。@mLstudent33与使用where
的方式完全相同,如中所示。根据,where(x)
相当于asarray(x).nonzero()
。只要我只有一个条件,这就行了。如果我想搜索“x==numpy.array(0,2,7)”,该怎么办?结果应该是数组([1,2,3,5,9])。但是我怎么能得到这个呢?你可以用:numpy.flatnorzero(numpy.logical\u或(numpy.logical\u或(x==0,x==2,x==7))
你可以用它来访问零元素:a[a==0]=epsilon
这应该是公认的答案,因为这是检查条件的nonzero
方法的建议用法。
>>> 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])
>>> 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]))