2013-02-04 50 views
2

如何將布爾數組轉換爲可迭代的索引?從布爾數組中設置Python numpy索引

例如,

import numpy as np 
import itertools as it 
x = np.array([1,0,1,1,0,0]) 
y = x > 0 
retval = [i for i, y_i in enumerate(y) if y_i] 

是否有更好的辦法嗎?

回答

3

嘗試np.wherenp.nonzero

x = np.array([1, 0, 1, 1, 0, 0]) 
np.where(x)[0] # returns a tuple hence the [0], see help(np.where) 
# array([0, 2, 3]) 
x.nonzero()[0] # in this case, the same as above. 

help(np.where)help(np.nonzero)

可能值得注意的是,在np.where頁面中提到,對於1D x而言,它基本上等同於問題中的longform。

+0

我知道還有更好的辦法!我看着「np.index *」,但沒有找到任何東西。 –