numpy.where(condition,x,y)

详细用法请大家详见官方文档

这里举几个例子

import numpy as np
a=np.array([1,2,3,4,5])
print(np.where(a<3))#查找小于3的元素的位置

结果

(array([0, 1], dtype=int64),)

注意输入的数组必须是numpy数组,list是不支持的

二维数组的例子

>>> x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))
>>> x[np.where( x > 3.0 )]               # Note: result is 1D.
array([ 4.,  5.,  6.,  7.,  8.])
>>> np.where(x < 5, x, -1)               # Note: broadcasting.
array([[ 0.,  1.,  2.],
       [ 3.,  4., -1.],
       [-1., -1., -1.]])
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐