numpy:搜索数组中的第一个和最后一个索引
问题描述:
我使用Python和numpy
。numpy:搜索数组中的第一个和最后一个索引
我有一个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
?
答
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]]