having an array like this for example:
[1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1]
What's the fastest way in Python to get the non-zero elements organized in a list where each element contains the indexes of blocks of continuous non-zero values?
Here the result would be a list containing many arrays:
([0, 1, 2, 3], [9, 10, 11], [14, 15], [20, 21])
A trivial change to my answer at Finding the consecutive zeros in a numpy array gives the function
find_runs
:For example,
If the value
1
in your example was not representative, and you really want runs of any non-zero values (as suggested by the text of the question), you can changenp.equal(a, value)
to(a != 0)
and change the arguments and comments appropriately. E.g.For example,
You can use
np.split
, once you know the interval of non-zeros' lengths and the corresponding indices inA
. AssumingA
as the input array, the implementation would look something like this -Sample input, output -
Have a look at
scipy.ndimage.measurements.label
:indices
contains exactly what you asked for. Note that, depending on your ultimate goal,labelled
might also give you useful (extra) information.