Python : Numpy: where()函数

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和同一个索引位置一样才会认为==成立。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值