numpy.where#

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

根據 condition,從 xy 中選擇並回傳元素。

注意

當僅提供 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 被省略時呼叫的函數

Notes

如果所有陣列都是 1 維的,則 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]])