假设您有1d numpy数组:
[0,0,0,0,0,1,2,3,0,0,0,0,4,5,0,0,0]
如何使用for循环不创建以下组?
[1,2,3], [4,5]
答案 0 :(得分:2)
这是使用np.split
的一种方法:
a
# array([0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 4, 5, 0, 0, 0])
### find nonzeros
z = a!=0
### find switching points
z[1:] ^= z[:-1]
### split at switching points and discard zeros
np.split(a, *np.where(z))[1::2]
# [array([1, 2, 3]), array([4, 5])]