根据条件,从x或y返回元素。
如果只给出条件,则返回condition.nonzero()
。
参数: | condition:array_like,bool
当为True时,产量x,否则产生y。
x,y:array_like,可选
要选择的值。x和y需要具有与条件相同的形状。
|
---|
返回: | out:ndarray的数组或元组
如果指定x和y,则输出数组包含x的元素,其中条件从y。
如果仅给出条件,则返回元组condition.nonzero() ,其中条件为True。
|
---|
numpy.where()分两种调用方式: #知乎回答
1、三个参数np.where(cond,x,y):满足条件(cond)输出x,不满足输出y
2、一个参数np.where(arry):输出array中‘真’值的坐标(‘真’也可以理解为非零)
例子:
>>> np.where([[True, False], [True, True]], # condition
... [[1, 2], [3, 4]], # X
... [[9, 8], [7, 6]]) # Y
array([[1, 8],
[3, 4]])
>>> 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.]])