查找具有邻域的特定数组元素

2024-05-14 06:09:51 发布

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

我有以下numpy数组:

data =   [[2 1 2 0 3 0 1 0 1]
          [4 0 1 2 3 3 4 4 1]
          [2 3 2 2 2 1 2 0 3]
          [0 3 1 3 4 0 0 3 2]]

data = np.array(data)

我想写一个高效的函数(就执行时间而言),它返回具有特定值的元素的索引,并具有另一个值的邻居。e、 g.对上述数据运行函数find_elements(data, 3, 2)应返回以下结果:

result = [(4, 1), (1, 2)]

enter image description here

到目前为止,我已经尝试过:

def find_elements(data, value, neighbor_value):
    result = []
    ix = np.isin(data, [value])
    a_ix = np.where(ix)

    for y, x in itertools.izip(a_ix[0], a_ix[1]):
        if y == 0 or y == data.shape[0] - 1 or x == 0 or x == data.shape[1] - 1:
            continue

        if data[y - 1, x] == neighbor_value or data[y + 1, x] == neighbor_value or data[y, x - 1] == neighbor_value or data[y, x + 1] == neighbor_value:
            result.append((x, y))

    return result

问题:有没有办法在numpy筛选中指定相邻元素?或者在任何提供此功能的库中是否已经有内置函数


Tags: or函数numpy元素dataifvaluenp