计算numpy数组中的元素连续满足条件的次数 [英] Count the number of times elements in a numpy array consecutively satisfy a condition
本文介绍了计算numpy数组中的元素连续满足条件的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个numpy
数组,如下所示:
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])
和常数b=6
我正在搜索数字c
,该数字由a
中的元素连续小于b
的次数等于或大于2的次数定义.
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.
因此在此示例中为c=3
我没有有效的代码,这就是为什么我在这里问这个问题.基于上一个问题,我可以使用np.sum(a<b)
来获取a<b
的次数.
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
现在,我想计算a
连续两次小于b
的次数.
Now I want to count the number of times where a
is two or more times consecutively less than b
.
以下是此示例a
中的3个组的说明:
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
推荐答案
您可以使用numpy
遮罩和itertools.groupby
.
from itertools import groupby
b = 6
sum(len(list(g))>=2 for i, g in groupby(a < b) if i)
#3
这篇关于计算numpy数组中的元素连续满足条件的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文