加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:46:17 所属栏目:Python 来源:网络整理
导读:考虑一个条目,其条目仅由-1或1组成.如何获得仅包含1且最小长度为t的所有切片的范围(例如t = 3) 例: a=np.array([-1,-1,1,1],dtype=int) aarray([-1,1]) 然后,期望输出fort = 3将是[(2,7),(11,15)]. 最佳答案 使用 np.diff 和 np.where 的一种方法 # Append

考虑一个条目,其条目仅由-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)].

最佳答案
使用np.diffnp.where的一种方法 –

# 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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读