2013-02-28 128 views
2

我使用Python和numpynumpy:搜索數組中的第一個和最後一個索引

我有一個numpy的陣列b

b = np.array([True,True,True,False,False,True,True,False,True,True,True,True,False]) 

我需要找到第一和最後一個索引,其中b等於True

對於這個exsample:

out_index: [0,2] 
      [5,6] 
      [8,11] 

可有人請建議,我怎麼out_index

回答

6
b = np.array([True,True,True,False,False,True,True,False,True,True,True,True,False]) 
idx = np.argwhere(np.diff(np.r_[False, b, False])).reshape(-1, 2) 
idx[:, 1] -= 1 
print idx 

輸出:

[[ 0 2] 
[ 5 6] 
[ 8 11]] 
相關問題