numpy.select#

numpy.select(condlist, choicelist, default=0)[原始碼]#

根據條件,從 choicelist 中的元素傳回陣列。

參數:
condlist布林 ndarray 列表

條件列表,決定從 choicelist 中的哪個陣列取得輸出元素。當滿足多個條件時,使用在 condlist 中遇到的第一個條件。

choicelistndarray 列表

从中取得輸出元素的陣列列表。它必須與 condlist 的長度相同。

default純量,可選

當所有條件評估為 False 時,插入 output 的元素。

傳回:
outputndarray

位置 m 的輸出是 choicelist 中陣列的第 m 個元素,其中 condlist 中相應陣列的第 m 個元素為 True。

另請參閱

where

根據條件從兩個陣列之一傳回元素。

take, choose, compress, diag, diagonal

範例

>>> import numpy as np

從 0 到 5 (包含 5) 的整數陣列開始,小於 3 的元素會被否定,大於 3 的元素會被平方,而不符合任一條件的元素 (正好是 3) 會被替換為 default42

>>> x = np.arange(6)
>>> condlist = [x<3, x>3]
>>> choicelist = [x, x**2]
>>> np.select(condlist, choicelist, 42)
array([ 0,  1,  2, 42, 16, 25])

當滿足多個條件時,使用在 condlist 中遇到的第一個條件。

>>> condlist = [x<=4, x>3]
>>> choicelist = [x, x**2]
>>> np.select(condlist, choicelist, 55)
array([ 0,  1,  2,  3,  4, 25])