我正在尝试使用 numpy.where(condition[, x, y])
函数。
根据numpy文档,如果你只给一个数组作为输入,它应该返回数组中非零元素(即“True”)的索引:
如果只有 condition 被给出,返回元组 condition.nonzero(),其中包含 condition 为真的索引。
但是如果我尝试它,它会返回一个包含两个元素的 元组,第一个元素是想要的索引列表,第二个元素是空元素:
>>> import numpy as np
>>> array = np.array([1,2,3,4,5,6,7,8,9])
>>> np.where(array>4)
(array([4, 5, 6, 7, 8]),) # notice the comma before the last parenthesis
所以问题是:为什么?这种行为的目的是什么?在什么情况下会有用呢?
实际上,为了得到想要的索引列表,我必须添加索引,如np.where(array>4)[0]
,看起来...“丑陋”。
补充说明
我理解(根据某些答案)它实际上是只有一个元素的元组。但我仍然不明白为什么要以这种方式输出。为了说明这不是理想的方法,请考虑以下错误(这也是我提出问题的原因):
>>> import numpy as np
>>> array = np.array([1,2,3,4,5,6,7,8,9])
>>> pippo = np.where(array>4)
>>> pippo + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "int") to tuple
所以你需要进行一些索引才能访问实际的索引数组:
>>> pippo[0] + 1
array([5, 6, 7, 8, 9])
np.argwhere
怎么样? - Divakarnp.flatnonzero
№╝їт«ЃТЅДУАїуџёТЊЇСйюТў»a.ravel().nonzero()[0]
сђѓ - hpaulj