Skip to content Skip to sidebar Skip to footer

Count Consecutive Equal Values In Array

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 consecut

Solution 1:

Here is one option adapted from this answer:

def count_consecutive(arr, n):
    # pad a withFalseatboth sides for edge cases whenarray starts or ends with n
    d = np.diff(np.concatenate(([False], arr == n, [False])).astype(int))
    # subtract indices whenvalue changes fromFalsetoTruefrom indices wherevalue changes fromTruetoFalsereturn np.flatnonzero(d ==-1) - np.flatnonzero(d ==1)

count_consecutive(a, 5)
# array([2, 1, 3])

Solution 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]

Post a Comment for "Count Consecutive Equal Values In Array"