Parameters: | condition : array_like, bool When True, yield x, otherwise yield y |
---|
有条件参数时,条件为真输出X,为假输出Y
当只有条件参数时,输出条件参数中非零项,行矩阵和列矩阵
>>> np.where([[True, False], [True, True]],
... [[1, 2], [3, 4]],
... [[9, 8], [7, 6]])
array([[1, 8],
[3, 4]])
>>> np.where([[0, 1], [1, 0]])
(array([0, 1]), array([1, 0]))
参考一下博客https://www.cnblogs.com/massquantity/p/8908859.html
>>> a = np.array([2,4,6,8,10])
>>> np.where(a > 5) # 返回索引
(array([2, 3, 4]),)
>>> a[np.where(a > 5)] # 等价于 a[a>5]
array([ 6, 8, 10])
>>> np.where([[0, 1], [1, 0]])
(array([0, 1]), array([1, 0]))
需要补充的是,where函数只有condition的时候,输入的a是N维的时候,返回的元组就会有N个矩阵。
比如:
>>> import numpy as np
>>> a = np.array([[23,4,6,7],[4,5,7,34]])
>>> np.where(a>5)
(array([0, 0, 0, 1, 1]), array([0, 2, 3, 2, 3]))
>>>
返回的元组包含两个矩阵,一个是行索引,一个是列索引。
在where()中是两个矩阵的时候:
ious = np.array([[1,2,4,7,89,9],[7,5,3,71,6,1],[7,4,2,46,854,8]])
>>> argmax = ious.argmax(axis=0)
>>> argmax
array([1, 1, 0, 1, 2, 0])
>>> gt_max = ious[argmax, np.arange(ious.shape[1])]
>>> gt_max
array([ 7, 5, 4, 71, 854, 9])
>>> np.where(ious == gt_max)
(array([0, 0, 1, 1, 1, 2, 2]), array([2, 5, 0, 1, 3, 0, 4]))
这里使用了==必须要ious和gt_max和同一个索引位置一样才会认为==成立。