Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如何将布尔数组转换为可迭代的索引?
例如,
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]
有没有更好的方法?
尝试np.where或np.nonzero。
np.where
np.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)。
help(np.where)
help(np.nonzero)
可能值得注意的是,在np.where页面中它提到对于 1Dx它基本上等同于问题中的长格式。
x