python 连续三个数满足条件_python – 在numpy数组中找到满足条件的大量连续值

这是一个基于numpy的解决方案。

我认为(?)应该比其他选项快。希望很清楚

然而,它确实需要与各种基于发生器的解决方案相同的存储空间。只要您可以在内存中保存数据的单个临时副本(对于diff),以及与数据(1位元素)相同长度的布尔数组,则应该非常有效…

import numpy as np

def main():

# Generate some random data

x = np.cumsum(np.random.random(1000) - 0.5)

condition = np.abs(x) < 1

# Print the start and stop indicies of each region where the absolute

# values of x are below 1, and the min and max of each of these regions

for start, stop in contiguous_regions(condition):

segment = x[start:stop]

print start, stop

print segment.min(), segment.max()

def contiguous_regions(condition):

"""Finds contiguous True regions of the boolean array "condition". Returns

a 2D array where the first column is the start index of the region and the

second column is the end index."""

# Find the indicies of changes in "condition"

d = np.diff(condition)

idx, = d.nonzero()

# We need to start things after the change in "condition". Therefore,

# we'll shift the index by 1 to the right.

idx += 1

if condition[0]:

# If the start of condition is True prepend a 0

idx = np.r_[0, idx]

if condition[-1]:

# If the end of condition is True, append the length of the array

idx = np.r_[idx, condition.size] # Edit

# Reshape the result into two columns

idx.shape = (-1,2)

return idx

main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值