python - numpy 中有没有一种方法可以验证一个数组是否包含在另一个数组中?

标签 python numpy

我想验证 numpy 数组是否是另一个数组中的连续序列。

例如

a = np.array([1,2,3,4,5,6,7])
b = np.array([3,4,5])
c = np.array([2,3,4,6])

预期结果是:

is_sequence_of(b, a) # should return True
is_sequence_of(c, a) # should return False

我想知道是否有一个 numpy 方法可以做到这一点。

最佳答案

方法#1

我们可以将其与 np.searchsorted 一起使用 -

def isin_seq(a,b):
    # Look for the presence of b in a, while keeping the sequence
    sidx = a.argsort()
    idx = np.searchsorted(a,b,sorter=sidx)
    idx[idx==len(a)] = 0
    ssidx = sidx[idx]
    return (np.diff(ssidx)==1).all() & (a[ssidx]==b).all()

请注意,这假设输入数组没有重复项。

示例运行 -

In [42]: isin_seq(a,b) # search for the sequence b in a
Out[42]: True

In [43]: isin_seq(c,b) # search for the sequence b in c
Out[43]: False

方法#2

另一个带有 skimage.util.view_as_windows -

from skimage.util import view_as_windows

def isin_seq_v2(a,b):
    return (view_as_windows(a,len(b))==b).all(1).any()

方法#3

这也可以被视为模板匹配问题,因此,对于 int 数字,我们可以使用 OpenCV 的内置函数进行模板匹配:cv2.matchTemplate (受到 this post 的启发),就像这样 -

import cv2 
from cv2 import matchTemplate as cv2m

def isin_seq_v3(arr,seq):
    S = cv2m(arr.astype('uint8'),seq.astype('uint8'),cv2.TM_SQDIFF)
    return np.isclose(S,0).any()

方法#4

我们的方法可以受益于基于短路的方法。因此,我们将使用一个带有 numba 的函数来提高性能效率,就像这样 -

from numba import njit

@njit
def isin_seq_numba(a,b):
    m = len(a)
    n = len(b)
    for i in range(m-n+1):
        for j in range(n):
            if a[i+j]!=b[j]:
                break                
        if j==n-1:
            return True
    return False

关于python - numpy 中有没有一种方法可以验证一个数组是否包含在另一个数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58765272/

相关文章:

python - numpy.searchsorted 二维数组

python - 在Python中导入email.utils库

php - 图像大小调整 Web 服务

python - 用空格填充多个字符 - python

python - 如何沿一个轴获取 NumPy 数组中最大元素的索引

numpy - 计算 xarray 中每个网格点的百分位

python - 如何删除类似的 alembic 版本?

Python 子进程 : pipe an image blob to imagemagick shell command

python - 堆叠 2D numpy 数组以使用 nanmean

python - 将 numpy 数组列表转换为 json 以从 flask api 返回