## Count number of clusters of non-zero values in Python?

Question

My data looks something like this:

```
a=[0,0,0,0,0,0,10,15,16,12,11,9,10,0,0,0,0,0,6,9,3,7,5,4,0,0,0,0,0,0,4,3,9,7,1]
```

Essentially, there's a bunch of zeroes before non-zero numbers and I am looking to count the number of groups of non-zero numbers separated by zeros. In the example data above, there are 3 groups of non-zero data so the code should return 3.

- Number of zeros between groups of non-zeros is variable

Any good ways to do this in python? (Also using Pandas and Numpy to help parse the data)

Show source

## Answers ( 5 )

With

`a`

as the input array, we could have a vectorized solution -Alternatively for performance, we might use

`np.count_nonzero`

which is very efficient to count bools as is the case here, like so -Basically, we get a mask of

`non-zeros`

and count rising edges. To account for the first element that could be non-zero too and would not have any rising edge, we need to check it and add to the total sum.Also, please note that if input

`a`

is a list, we need to use`m = np.asarray(a)!=0`

instead.Sample runs for three cases -

simple python solution, just count changes from 0 to non-zero, by keeping track of the previous value (rising edge detection):

You may achieve it via using

`itertools.groupby()`

withlist comprehensionexpression as:`np.concatenate`

`a == 0`

`np.diff`

`sum`

demonstrationtiming`a = np.random.choice((0, 1), 100000)`

code