where()函數是numpy模塊中的一個函數,它的語法如下:
where(condition, [x, y])
有點類似python中的三目運算符:
x = a if condition else b
[x,y]是可選參數,舉個例子:
import numpy as np
arr = np.random.randint(0,10,(3,5))
print (arr)
np.where(arr<5)
[[8 6 7 8 8]
[1 7 1 8 6]
[8 9 7 3 6]]
(array([1, 1, 2], dtype=int64), array([0, 2, 3], dtype=int64))
現在加上可選條件,讓數組中大於5的數字全部變成5
import numpy as np
arr = np.random.randint(0,10,(3,5))
print (arr)
np.where(arr>5,5,arr)
[[3 3 0 2 1]
[2 3 0 2 3]
[6 1 0 6 4]]
…
array([[3, 3, 0, 2, 1],
[2, 3, 0, 2, 3],
[5, 1, 0, 5, 4]])