numpy.where#

numpy.where(condition, [x, y, ]/)#

根据 conditionxy 中返回选定的元素。

注意

当只提供 condition 时,此函数是 np.asarray(condition).nonzero() 的简写。建议直接使用 nonzero,因为它对子类表现正确。本文档的其余部分仅涵盖提供了所有三个参数的情况。

参数
conditionarray_like, bool

当为 True 时,返回 x;否则,返回 y

x, yarray_like

从中选择的值。xycondition 需要能够广播到某个形状。

返回
outndarray

一个数组,其中 condition 为 True 的位置的元素来自 x,其他位置的元素来自 y

另请参阅

choose
nonzero

当 x 和 y 被省略时调用的函数

注释

如果所有数组都是 1-D 的,where 等价于

[xv if c else yv
 for c, xv, yv in zip(condition, x, y)]

示例

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.where(a < 5, a, 10*a)
array([ 0,  1,  2,  3,  4, 50, 60, 70, 80, 90])

这也可以用于多维数组

>>> np.where([[True, False], [True, True]],
...          [[1, 2], [3, 4]],
...          [[9, 8], [7, 6]])
array([[1, 8],
       [3, 4]])

x、y 和 condition 的形状会一起广播

>>> x, y = np.ogrid[:3, :4]
>>> np.where(x < y, x, 10 + y)  # both x and 10+y are broadcast
array([[10,  0,  0,  0],
       [10, 11,  1,  1],
       [10, 11, 12,  2]])
>>> a = np.array([[0, 1, 2],
...               [0, 2, 4],
...               [0, 3, 6]])
>>> np.where(a < 4, a, -1)  # -1 is broadcast
array([[ 0,  1,  2],
       [ 0,  2, -1],
       [ 0,  3, -1]])