1

I have a numpy array like so:

array([100, 100, 100, 100, 100, 200, 100, 100, 100, 100, 100, 100, 100,
    100, 200, 100, 100, 100, 100, 100, 100, 100, 100, 200, 100, 100,
    100, 100, 100, 100, 100, 200, 100, 100, 100, 100, 100, 100, 100,
    100, 200, 100, 100, 100, 100, 100, 100, 100, 100, 200, 100, 100,
    100, 100, 100, 100, 100, 300, 100, 100, 100])

I need to count the consecutive number of '100' elements. The '100' elements are separated by values greater than 100.

Output should look like:

[5,8,8,7,8,8,7,3]
Mohit Motwani
  • 4,662
  • 3
  • 17
  • 45
Mazz
  • 770
  • 3
  • 11
  • 23
  • Using a for loop to append a count to a list for i in c: if(i == 100): count += 1 list.append(count) – Mazz Mar 13 '19 at 11:50
  • You could use `np.where()` to find the idx with the values, and then split the result array into sub-arrays with consecutive integers (c.f. https://stackoverflow.com/questions/2361945/detecting-consecutive-integers-in-a-list#comment71456493_2361991) and finally, take the length of each sub-arrays. – Mathieu Mar 13 '19 at 11:53

3 Answers3

3

Here's a simple python script:

arr = [100, 100, 100, 100, 100, 200, 100, 100, 100, 100, 100, 100, 100,
    100, 200, 100, 100, 100, 100, 100, 100, 100, 100, 200, 100, 100,
    100, 100, 100, 100, 100, 200, 100, 100, 100, 100, 100, 100, 100,
    100, 200, 100, 100, 100, 100, 100, 100, 100, 100, 200, 100, 100,
    100, 100, 100, 100, 100, 300, 100, 100, 100]

check = arr[0]
result = []
count = 0
for el in arr:
    if el == check:
        count+=1
    else:
        check = el
        if count>1:
            result.append(count)
        count = 1
result.append(count)

print(result)
[5, 8, 8, 7, 8, 8, 7, 3]
Mohit Motwani
  • 4,662
  • 3
  • 17
  • 45
2

Convert the numpy array into a list like this :

a = [100, 100, 100, 100, 100, 200, 100, 100, 100, 100, 100, 100, 100, 100, 200, 100, 100, 100, 100, 100, 100, 100, 100, 200, 100, 100, 100, 100, 100, 100, 100, 200, 100, 100, 100, 100, 100, 100, 100, 100, 200, 100, 100, 100, 100, 100, 100, 100, 100, 200, 100, 100, 100, 100, 100, 100, 100, 300, 100, 100, 100]

Try :

from itertools import groupby
b = [sum(1 for i in g) for k,g in groupby(a) if k==100]

OUTPUT :

b = [5, 8, 8, 7, 8, 8, 7, 3]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
2

Here's a way adapting @Jaime's solution in this post:

a = np.array([100, 100, 100, 100, 100, 200, 100, 100, 100, 100, 100, 100, 100,
100, 200, 100, 100, 100, 100, 100, 100, 100, 100, 200, 100, 100,
100, 100, 100, 100, 100, 200, 100, 100, 100, 100, 100, 100, 100,
100, 200, 100, 100, 100, 100, 100, 100, 100, 100, 200, 100, 100,
100, 100, 100, 100, 100, 300, 100, 100, 100])

c = a == 100
np.diff(np.where(np.concatenate(([c[0]], c[:-1] != c[1:], [True])))[0])[::2]
# array([5, 8, 8, 7, 8, 8, 7, 3])
yatu
  • 86,083
  • 12
  • 84
  • 139