2014-02-17 14 views
2

我是Numpy的新手。我想找到等於一組值的元素索引。例如,我知道這個作品:numpy找到好值的指數

>>> x = np.array([[0, 1], [2, 3], [4, 5]]) 
>>> x 
array([[0, 1], 
     [2, 3], 
     [4, 5]]) 
>>> x[np.where(x[:,0] == 2)] 
array([[2, 3]]) 

但是,爲什麼不工作?我想這應該是一個直接的延伸。沒有?

>>> x[np.where(x[:,0] == [2,4])] 
array([], shape=(0, 2), dtype=int64) 
+0

你正在尋找這兩個元素是單獨的,還是一個2的順序跟一個4? – M4rtini

回答

0

你想

x[np.where(x[:,0] in [2,4])] 

這實際上可能不是有效numpy的

mask = numpy.in1d(x[:,0],[2,4]) 
x[mask] 

順便說一句,你可以重寫你的第一個條件

x[x[:,0] == 2] 
1

==沒有按沒有像那樣工作在;當給出兩個不同形狀的陣列時,它會嘗試根據broadcasting rules廣播比較。

如果你想確定一個數組的元素在元素的列表,你想in1d

>>> x = numpy.arange(9).reshape((3, 3)) 
>>> numpy.in1d(x.flat, [2, 3, 5, 7]) 
array([False, False, True, True, False, True, False, True, False], dtype=boo 
l) 
>>> numpy.in1d(x.flat, [2, 3, 5, 7]).reshape(x.shape) 
array([[False, False, True], 
     [ True, False, True], 
     [False, True, False]], dtype=bool) 
0

從你的問題,我認爲你的意思是,你要找到行,其中第一元素等於一些特殊值。你說的方式我認爲你的意思是x[:,0] in [2,4],而不是x[:,0] == [2,4],它仍然不會在np.where()工作。相反,你需要構建它是這樣的:

x[np.where((x[:,0] == 2) | (x[:,0] == 4))] 

由於這不能很好地擴展,你可能反而想嘗試在for循環做:

good_row =() 
good_values = [2,4] 
for val in good_values: 
    good_row = np.append(good_row,np.where(x[:,0] == val)) 

print x[good_row]