3

I have an array like

[0,0,0,0,1,1,1,1,0,0,0,0,1,1,0,0]

and I want to determine the number of non-zeros intervals. I know how I can do that of course in a for loop but I wonder if there is a nice numpy solution to it.

The method I am looking for is suppose to "collapse" the array whenever a value repeats itself. So the above array would become for example

[0,1,0,1,0]

for the sake of counting it would of course be sufficient to return just

[1,1]

but I'd like to know a general approach that might also be able to handle more than two different elements such as

[1,1,1,2,2,2,3,3,0,0,1,1,2,2]

or so.

0

1 Answer 1

1

One option is to pick up the values when there is a change with boolean indexing:

import numpy as np
a = np.array([1,1,1,2,2,2,3,3,0,0,1,1,2,2])

a[np.concatenate(([True], np.diff(a) != 0))]
# array([1, 2, 3, 0, 1, 2])

np.count_nonzero(a[np.concatenate(([True], np.diff(a) != 0))])
# 5

First case:

b = np.array([0,0,0,0,1,1,1,1,0,0,0,0,1,1,0,0])
​
b[np.concatenate(([True], np.diff(b) != 0))]
# array([0, 1, 0, 1, 0])

np.count_nonzero(b[np.concatenate(([True], np.diff(b) != 0))])
# 2
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.