Python Numpy.where() 函式
Sohaib Atiq
2023年1月30日
NumPy
-
numpy.where()語法 -
示例程式碼:
numpy.where(), 沒有[x, y]輸入 -
示例程式碼:
numpy.where()與 1-D 陣列的關係 -
示例程式碼:
numpy.where()與二維陣列的關係 -
示例程式碼:
numpy.where()有多個條件
numpy.where() 函式在沒有給出 x、y 的情況下,生成符合輸入條件的陣列索引;或者根據給定的條件從 x 或 y 中生成陣列元素。
numpy.where() 語法
numpy.where(condition, [x, y])
引數
condition |
array_like, True 或 False 如果條件是 True,則輸出包含 x 的元素,否則,輸出包含 y 的元素 |
x,y |
返回值產生的陣列 可以同時傳遞 (x, y) 或不傳遞 |
返回值
它返回一個陣列。如果條件為 True,結果包含 x 元素,如果條件為 False,結果包含 y 元素。
如果沒有給定 x, y,則返回陣列的索引。
示例程式碼:numpy.where(), 沒有 [x, y] 輸入
import numpy as np
m = np.array([1, 2, 3, 4, 5])
n = np.where(m > 3)
print(n)
輸出:
(array([3, 4], dtype=int64),)
它返回 m 的索引,其中元素大於 3 - a > 3。
如果你需要的是元素而不是索引。
示例程式碼:numpy.where() 與 1-D 陣列的關係
import numpy as np
m = np.where([True, False, True], [1,2,3], [4, 5, 6])
print(m)
輸出:
[1 5 3]
當條件是一個 1-D 陣列時,Numpy.where() 函式對條件陣列進行迭代,如果條件元素是 True,則從 x 中選擇元素,如果條件元素是 False,則從 y 中選擇元素。
示例程式碼:numpy.where() 與二維陣列的關係
import numpy as np
x = np.array([[10, 20, 30], [3, 50, 5]])
y = np.array([[70, 80, 90], [100, 110, 120]])
condition = np.where(x > 20, x, y)
print("Input array :")
print(x)
print(y)
print("Output array with condition applied:")
print(condition)
輸出:
Input array :
[[10 20 30]
[ 3 50 5]]
[[ 70 80 90]
[100 110 120]]
Output array with condition applied:
[[ 70 80 30]
[100 50 120]]
它將 x>20 的條件應用於 x 的所有元素,如果是 True,則輸出 x 的元素,如果是 False,則輸出 y 的元素。
我們做一個簡化的例子來說明它的工作原理。
import numpy as np
m = np.where(
[[True, False, True], [False, True, False]],
[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]],
)
print(m)
輸出:
[[ 1 8 3]
[10 5 12]]
示例程式碼:numpy.where() 有多個條件
我們也可以在 numpy.where() 函式中應用兩個或多個條件。
import numpy as np
m = np.array([1, 2, 3, 4, 5])
n = np.where((m > 1) & (m < 5), m, 0)
print(n)
輸出:
[0 2 3 4 0]
它應用 m > 1 和 m < 5 這兩個多重條件,如果元素滿足這兩個條件,則返回元素。
多重條件之間的邏輯不限於 AND(&),也接受 OR(|)。
import numpy as np
m = np.array([1, 2, 3, 4, 5])
n = np.where((m < 2) | (m > 4), m, 0)
print(n)
輸出:
[1 0 0 0 5]
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe