python - 在另一个数组中创建“条纹”的开始和结束索引的二维 numpy 数组。
问题描述
假设我有一个 1D numpy array of numbers myArray = ([1, 1, 0, 2, 0, 1, 1, 1, 1, 0, 0 ,1, 2, 1, 1, 1])
。
我想创建一个 2D numpy 数组,该数组描述任何连续 1 的“条纹”的第一个(第 1 列)和最后一个(第 2 列)索引,该索引的长度大于 2。因此对于上面的示例,二维数组应该如下所示:
indicesArray =
([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]
样品运行 -
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]
推荐阅读
- unity3d - (Unity2D) 增加和减少统计栏问题
- android - Android在片段活动中设置颜色过滤器
- c++ - 使用打印队列的元素
- (错误 C2760)
- ubuntu - Ubuntu 18.04 freezes after login
- git - 詹金斯管道 git checkout 不工作
- apache-spark - 无法使用 PySpark 从 Elasticsearch 读取
- c# - c#不能在代码中的资源中使用图片?
- python - 任务调度程序未运行 Selenium 脚本
- angular - 错误:mat-table 上的 FormArray --> 找不到路径控件(Angular 6)
- encoding - 你能用不是 utf8 的编码来编写 Perl 6 脚本吗?