Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

python - Count the number of times elements in a numpy array consecutively satisfy a condition

I have a numpy array as follows:

import numpy as np
a = np.array([1, 4, 2, 6, 4, 4, 6, 2, 7, 6, 2, 8, 9, 3, 6, 3, 4, 4, 5, 8])

and a constant number b=6

I am searching for a number c which is defined by the number of times the elements in a are less than b 2 or more times consecutively.

So in this example it c=3

I have no working code, that's why I am asking that here. Based on a previous question I can use np.sum(a<b) to get the number of times that a<b.

print(np.sum(a<b))
#12

Now I want to count the number of times where a is two or more times consecutively less than b.

Here is an illustration of the 3 groups in for this sample a:

1, 4, 2, 6, 4, 4, 6, 2, 7, 6, 2, 8, 9, 3, 6, 3, 4, 4, 5, 8  # numbers in a
1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0  # (a<b)
^^^^^^^-----^^^^-----------------------------^^^^^^^^^^---  # (a<b) 2+ times consecutively
   1         2                                    3
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use numpy masking and itertools.groupby.

from itertools import groupby

b = 6
sum(len(list(g))>=2 for i, g in groupby(a < b) if i)
#3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...