-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.

3
  • Certainly can be adapted: [sum(1 for _ in group) for key, group in itertools.groupby(a) if key == 5] Commented Feb 8, 2019 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. Commented Feb 8, 2019 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. :) Commented Feb 8, 2019 at 22:33

2 Answers 2

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])
Sign up to request clarification or add additional context in comments.

Comments

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]

1 Comment

Yes, I'm aware of itertools.groupby. Really looking for a numpy one, but thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.