Remove values ββif they are repeated in an array
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 define the number of intervals without zero. I know how I can do this, of course, in a for loop, but I wonder if it has a nice solution numpy
.
The method I'm looking for is supposed to "collapse" the array whenever the value is repeated. So the above array would become for example
[0,1,0,1,0]
for counting it would, of course, be enough to return only
[1,1]
but I would like to know a general approach that could also handle more than two different elements like
[1,1,1,2,2,2,3,3,0,0,1,1,2,2]
or so.
+3
source to share
1 answer
One option is to fetch values ββon 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
+1
source to share