2017-10-06 156 views
2

我有下面的代碼,這實際上是檢查是否有任何值小於0.5在數據中,將被替換爲-1,但我想檢查是否具體位置值假設只應檢查第10個值!我怎樣才能做到這一點,利用其中numpy的功能numpy.where數據位置以及條件

import numpy as np 
x = np.random.random((10,10)) 
x2 = np.where(x<0.5, x, -1) 
print(x2) 

這是多麼想。與掩模檢查第十列

import numpy as np 
x = np.random.random((10,10)) 
x2 = np.where(x<0.5 and (index of x is 9), x, -1) 
print(x2) 
+0

我真的不明白'我要檢查,如果一個特定的位置值假設10值只應checked',你能解釋一下嗎? – Silencer

+0

我做了更改,請參閱 –

+0

但x是一個矩陣... – Silencer

回答

2

單程切片後即

import numpy as np 
x = np.random.random((10,10)) 

選項1

mask = x[:, 9] <0.5 
x[:, 9][mask] = -1 

選項2

x[:,9] = np.where(x[:, 9] <0.5,x[:,9],-1) 

輸出:

array([[ 0.13291679, 0.36437627, 0.61680761, 0.47180988, 0.40779945, 
    0.21448173, 0.70938531, 0.88205403, 0.9007378 , -1.  ], 
    [ 0.18517135, 0.591143 , 0.20951978, 0.09811755, 0.53492105, 
    0.70484089, 0.87912825, 0.94987278, 0.98151354, -1.  ], 
    [ 0.55545461, 0.50936625, 0.26460411, 0.81739966, 0.07142206, 
    0.97005035, 0.08655628, 0.62414457, 0.42844278, 0.67848139], 
    [ 0.97279637, 0.32032396, 0.87051124, 0.01823881, 0.58417096, 
    0.39085964, 0.39753232, 0.49915164, 0.44284544, -1.  ], 
    [ 0.95868029, 0.39688236, 0.82069431, 0.30433585, 0.52959998, 
    0.88929817, 0.90156477, 0.09418035, 0.68805644, 0.97685649], 
    [ 0.11680575, 0.97914842, 0.34087048, 0.16332758, 0.0531713 , 
    0.18936729, 0.02451479, 0.25073047, 0.72354052, -1.  ], 
    [ 0.65997478, 0.60118864, 0.42100758, 0.16616609, 0.16181439, 
    0.83024903, 0.99521926, 0.45748708, 0.26720405, 0.92070836], 
    [ 0.99248054, 0.68889428, 0.30094476, 0.00427059, 0.27930388, 
    0.44895715, 0.3866733 , 0.40558292, 0.4394462 , -1.  ], 
    [ 0.98661531, 0.57641035, 0.17323863, 0.17630214, 0.27312168, 
    0.14315776, 0.10212816, 0.15961012, 0.55773218, -1.  ], 
    [ 0.68539788, 0.58486093, 0.12482709, 0.89666695, 0.83484223, 
    0.39818926, 0.66773542, 0.59832267, 0.28018467, -1.  ]])