您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 在numpy数组中获取具有最小长度的相同条目的序列范围

5b51 2022/1/14 8:23:34 python 字数 1278 阅读 604 来源 www.jb51.cc/python

考虑一个条目,其条目仅由-1或1组成.如何获得仅包含1且最小长度为t的所有切片的范围(例如t = 3)例:>>>a=np.array([-1,-1,1,1,1,1,1,-1,1,-1,-1,1,1,1,1], dtype=int) >>> a array([-1, -1, 1, 1, 1, 1, 1, -1,

概述

考虑一个条目,其条目仅由-1或1组成.如何获得仅包含1且最小长度为t的所有切片的范围(例如t = 3)

例:

>>>a=np.array([-1,-1,1,1],dtype=int)
>>> a
array([-1,1])

然后,期望输出fort = 3将是[(2,7),(11,15)].

# Append with `-1s` at either ends and get the differentiation
dfa = np.diff(np.hstack((-1,a,-1)))

# Get the positions of starts and stops of 1s in `a`
starts = np.where(dfa==2)[0]
stops = np.where(dfa==-2)[0]

# Get valid mask for pairs from starts and stops being of at least 3 in length
valid_mask = (stops - starts) >= 3

# Finally collect the valid pairs as the output
out = np.column_stack((starts,stops))[valid_mask].tolist()

总结

以上是编程之家为你收集整理的python – 在numpy数组中获取具有最小长度的相同条目的序列范围全部内容,希望文章能够帮你解决python – 在numpy数组中获取具有最小长度的相同条目的序列范围所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶