Here is one vector approach -
np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size])
Run Example -
In [208]: a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0]) In [209]: np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size]) Out[209]: array([1, 3, 7, 1, 1, 2, 3, 2, 2])
Faster with boolean concatenation -
np.diff(np.flatnonzero(np.concatenate(([True], a[1:]!= a[:-1], [True] ))))
Runtime test
For setup, let me create a larger dataset with islands 0s and 1s and for a fair comparative analysis, as with this sample, let the length of the island vary between 1 and 7 -
In [257]: n = 100000