I have a numpy array of zeros and ones:
y=[1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1]
I want to calculate the indices of groups of ones (or zeros). So for the above example the result for groups of ones should be something similar to:
result=[(0,2), (8,9), (16,19)]
(How) Can I do that with numpy? I found nothing like a group-by function.
I experimented around with np.ediff1d, but couldn't figure out a good solution. Not that the array may or may not begin/end with a group of ones:
import numpy as np
y = [1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1]
mask = np.ediff1d(y)
starts = np.where(mask > 0)
ends = np.where(mask < 0)
I also found a partial solution here:
Find index where elements change value numpy
But that one only gives me the indices where the values change.
See Question&Answers more detail:
os