gpt4 book ai didi

python - 在另一个数组中创建 "streaks"开始和结束索引的 2D numpy 数组。

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:25 24 4
gpt4 key购买 nike

假设我有一个数字的一​​维 numpy 数组 myArray = ([1, 1, 0, 2, 0, 1, 1, 1, 1, 0, 0 ,1, 2, 1, 1, 1 ]).

我想创建一个 2D numpy 数组,它描述了任何长于 2 的连续 1 的“连胜”的第一个(第 1 列)和最后一个(第 2 列)索引。所以对于上面的例子,二维数组应该是这样的:

索引数组 =
([5, 8],
[13, 15])

因为第5、6、7、8位和第13、14、15位至少有3个连续的。

如有任何帮助,我们将不胜感激。

最佳答案

方法 #1

这是一种受 this post 启发的方法-

def start_stop(a, trigger_val, len_thresh=2):
# "Enclose" mask with sentients to catch shifts later on
mask = np.r_[False,np.equal(a, trigger_val),False]

# Get the shifting indices
idx = np.flatnonzero(mask[1:] != mask[:-1])

# Get lengths
lens = idx[1::2] - idx[::2]

return idx.reshape(-1,2)[lens>len_thresh]-[0,1]

sample 运行-

In [47]: myArray
Out[47]: array([1, 1, 0, 2, 0, 1, 1, 1, 1, 0, 0, 1, 2, 1, 1, 1])

In [48]: start_stop(myArray, trigger_val=1, len_thresh=2)
Out[48]:
array([[ 5, 8],
[13, 15]])

方法 #2

另一个 binary_erosion -

from scipy.ndimage.morphology import binary_erosion

mask = binary_erosion(myArray==1,structure=np.ones((3)))
idx = np.flatnonzero(mask[1:] != mask[:-1])
out = idx.reshape(-1,2)+[0,1]

关于python - 在另一个数组中创建 "streaks"开始和结束索引的 2D numpy 数组。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51259046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com