Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find same values in numpy array in a row

I’d like to find equal values in array(and their indexes) if they accure in a row more then 2 times.

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

so in this example I would find value "2" accured 4 times from position "8". Is there any build in function to do that?

I found the way with collections.Counter

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

collections.Counter(a)
# Counter({0: 3, 1: 4, 3: 2, 5: 1, 4: 1})

but this is not what I am looking for.
Of course I can write a loop and compare two values and then count them, but may be there is a more elegant solution?

>Solution :

Find consecutive runs and length of runs with condition

import numpy as np

arr = np.array([0, 3, 0, 1, 0, 1, 2, 1, 2, 2, 2, 2, 1, 3, 4])

res = np.ones_like(arr)
np.bitwise_xor(arr[:-1], arr[1:], out=res[1:])  # set equal, consecutive elements to 0
#np.not_equal(arr[:-1], arr[1:], out=res[1:])   # us this instead for np.floats
idxs = np.flatnonzero(res)                      # get indices of non zero elements
values = arr[idxs]
counts = np.diff(idxs, append=len(arr))         # difference between consecutive indices are the length

cond = counts > 2
values[cond], counts[cond], idxs[cond]

Output

(array([2]), array([4]), array([8]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading