-1

Say I have the following numpy array:

a = np.array([1,5,5,2,3,6,5,2,5,5,5])

I'm trying to come up with a numpy solution to count the amount of times a given value appears consecutively. So, for example for number 5 I'd like to get:

array([2,1,3])

As it appears consecutively 3 times in the array, with the specified amount of repetitions on each time.

yatu
  • 86,083
  • 12
  • 84
  • 139
  • Certainly can be adapted: `[sum(1 for _ in group) for key, group in itertools.groupby(a) if key == 5]` – Ondrej K. Feb 08 '19 at 22:17
  • There's another answer with GroupBy... Like I've already said looking for a numpy one. The one I was making reference to was the other one. – yatu Feb 08 '19 at 22:29
  • Yeah, sorry, just seen the question in review and saying that other answer could be adapted (you can can construct a new array with that list), not necessarily what you wanted, but it can be done. :) – Ondrej K. Feb 08 '19 at 22:33

2 Answers2

5

Here is one option adapted from this answer:

def count_consecutive(arr, n):
    # pad a with False at both sides for edge cases when array starts or ends with n
    d = np.diff(np.concatenate(([False], arr == n, [False])).astype(int))
    # subtract indices when value changes from False to True from indices where value changes from True to False
    return np.flatnonzero(d == -1) - np.flatnonzero(d == 1)

count_consecutive(a, 5)
# array([2, 1, 3])
Psidom
  • 209,562
  • 33
  • 339
  • 356
2

If you are okay with list then groupby can be used

from itertools import groupby
a=[1,5,5,2,3,6,5,2,5,5,5]
[len(list(v)) for k,v in groupby(a) if k==5]

Output

[2, 1, 3]
mad_
  • 8,121
  • 2
  • 25
  • 40