在布尔数组NumPy中保持前导岛和尾随岛为真

2024-06-16 11:33:29 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个一维纽比阵列。在

a = np.array([True True True False False False False True True False True False False False False False False True True])

实验结果:

^{pr2}$

为清晰起见编辑: 如何(1)将真值的“孤岛”保持在1d数组的前导和尾随位置,而(2)对于不在1d数组前导或尾随“孤岛”中的真值,将所有其他真值转换为False?在

我试过一个明显的非有效答案,那就是天真地重复一遍,但我还是觉得有更好的解决办法。有人有更好的主意吗?在

谢谢你的阅读!!!:)


Tags: 答案falsetrue编辑np数组array主意
3条回答

方法1

这里有一种方法使用^{}^{}来检测岛的启动和停止索引-

def fill_inner_islands(a):
    acc = np.maximum.accumulate
    start = a.argmax()
    end = a.size-a[::-1].argmax()
    a0 = ~a[start:end]
    a[start:end] = ~(acc(a0) & acc(a0[::-1])[::-1])

样本运行-

案例1:

^{pr2}$

案例2:

In [144]: a.astype(int)
Out[144]: array([1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0])

In [145]: fill_inner_islands(a)

In [146]: a.astype(int)
Out[146]: array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0])

案例三:

In [148]: a.astype(int)
Out[148]: array([1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0])

In [149]: fill_inner_islands(a)

In [150]: a.astype(int)
Out[150]: array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0])

方法2

更简单的方法-

def fill_inner_islands_v2(a):
    # Get stop and end indices of leading and trailing islands.
    # We do this by using one-off shifted slices and looking for the fall
    # in forward direction and fall in flipped direction   
    start = (a[1:] < a[:-1]).argmax()+1
    end = a.size - 1 - (a[:-1][::-1] < a[1:][::-1]).argmax()

    # Get the slice within those indices and assign as all False
    if ~a[start:end].all(): # To handle all True in input array
        a[start:end] = 0

这个问题的任何解决方案都涉及到迭代。这里有一个没有任何显式循环:

b = a.tolist()
start = b.index(False)
end = b[::-1].index(False)
if end:
    a[start : -end] = False
else:
    a[start : ] = False
>>> a
array([ True,  True,  True, False, False, False, False,  True,  True,
       False,  True, False, False, False, False, False, False,  True,  True], dtype=bool)

假设数组以True开头和结尾;找到True False,False True与np.差异

^{pr2}$

找到这些断裂的指数np.哪里在

>>> c = np.where(b)
>>> c = c[0]
>>> c
array([ 2,  6,  8,  9, 10, 16], dtype=int64)
>>>
>>> # c = b.nonzero()[0]

同样,假设数组以True开始和结束-您只关心第一个和最后一个中断

>>> x, y = c[0], c[-1]
>>> x, y
(2, 16)
>>>

使用作业左侧的索引

 >>> a[x+1:y] = False
>>> a
array([ True,  True,  True, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False,  True,  True], dtype=bool)
>>> 

相关问题 更多 >