np.where使用:根據條件生成新的陣列
阿新 • • 發佈:2018-12-25
np.where 函式是三元表示式 x if condition else y的向量化版本
result = np.where(cond,xarr,yarr)
當符合條件時是x,不符合是y,常用於根據一個數組產生另一個新的陣列。
栗子:假設有一個隨機數生成的矩陣,希望將所有正值替換為2,負值替換為-2
arr = np.random.randn(4,4)
arr
np.where(arr>0,2,-2)
arr = np.random.randn(4,4)
arr
Out[51]:
array([[ 0.04150406, 1.27790573, -0.25917274, -1.25604622],
[ 0.8797799 , 1.84828821, -1.21709272, -0.41767649],
[-0.71758894, -0.70595454, 1.72330333, 0.18559916],
[-2.19529605, 2.11615947, -0.13563148, -1.41532576]])
np.where(arr>0,2,-2)
Out[52]:
array([[ 2, 2, -2, -2],
[ 2, 2, -2, -2],
[-2, -2, 2, 2],
[-2, 2, -2, -2]])