get index of the first block of at least n consecutive False values in boolean array(获取布尔数组中至少 n 个连续 False 值的第一个块的索引)
问题描述
我有一个 numpy
布尔数组
w=np.array([True,False,True,True,False,False,False])
我想获取第一次有 n_at_least
错误值的索引.比如这里
I would like to get the index of the first time there are at n_at_least
false values.
For instance here
`n_at_least`=1 -> desired_index=1
`n_at_least`=3 -> desired_index=4
我试过了
np.cumsum(~w)
每次遇到 False
值时都会增加.但是,当遇到 True
时,计数器不再从 0 开始,所以我只得到 False
元素的总数,而不是最后一个连续元素的计数.
which does increase every time a False
value is encountered.
However, when True
is encountered the counter is not starting from 0 again so I only get the total count of False
elements rather than the count of the last consecutive ones.
推荐答案
我认为对于这种线性搜索操作,python 实现是可以的.我的建议是这样的:
I think for this linear search operation a python implementation is ok. My suggestion looks like this:
def find_block(arr, n_at_least=1):
current_index = 0
current_count = 0
for index, item in enumerate(arr):
if item:
current_count = 0
current_index = index + 1
else:
current_count += 1
if current_count == n_at_least:
return current_index
return None # Make sure this is outside for loop
运行此函数会产生以下输出:
Running this function yields the following outputs:
>>> import numpy
>>> w = numpy.array([True, False, True, True, False, False, False])
>>> find_block(w, n_at_least=1)
1
>>> find_block(w, n_at_least=3)
4
>>> find_block(w, n_at_least=4)
>>> # None
这篇关于获取布尔数组中至少 n 个连续 False 值的第一个块的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取布尔数组中至少 n 个连续 False 值的第一个块的索引


基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01