You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何快速获取NumPy二维数组中元素的四邻域值?

在NumPy中便捷获取数组某位置四邻域值的方法

先重现你的数组场景:

import numpy as np
np.random.seed(100)
a = np.random.randint(0, 100, (5,5))

数组内容:

array([[ 8, 24, 67, 87, 79],
       [48, 10, 94, 52, 98],
       [53, 66, 98, 14, 34],
       [24, 15, 60, 58, 16],
       [ 9, 93, 86,  2, 27]])

针对你手动索引四邻域繁琐的问题,有两种更便捷的实现方式:

方法1:偏移量批量索引

通过定义四邻域的偏移量数组,一次性计算并获取所有邻域值,无需逐个编写索引:

x, y = 2, 3  # 目标位置,对应值14
# 定义上下左右的偏移量(行偏移, 列偏移),顺序可按需调整
offsets = [(-1, 0), (1, 0), (0, -1), (0, 1)]  # 上、下、左、右

# 批量计算邻域索引并取值
neighbors = a[x + np.array([dx for dx, dy in offsets]), 
              y + np.array([dy for dx, dy in offsets])]
print(neighbors)  # 输出:array([52, 58, 98, 34])

如果要和你原代码的变量对应(up_val是下方、bott_val是上方),只需调整偏移量顺序:

offsets = [(1, 0), (-1, 0), (0, 1), (0, -1)]  # 对应原代码的up、bott、left、right
neighbors = a[x + np.array([dx for dx, dy in offsets]), 
              y + np.array([dy for dx, dy in offsets])]
# 此时 neighbors[0] = up_val, neighbors[1] = bott_val, neighbors[2] = left_val, neighbors[3] = right_val

方法2:3x3子数组提取(直观但需注意边界)

先截取目标位置所在的3x3子数组,再从中提取上下左右四个值:

x, y = 2, 3
# 截取包含目标的3x3区域
sub_arr = a[x-1:x+2, y-1:y+2]
# 提取对应位置:上、下、左、右
neighbors = [sub_arr[0,1], sub_arr[2,1], sub_arr[1,0], sub_arr[1,2]]
print(neighbors)  # 输出:[52, 58, 98, 34]

这种方法直观,但仅适用于目标位置不在数组边缘的情况,否则切片会触发索引越界错误。

边界处理

如果目标位置在数组边缘(比如x=0、x=4或y=0、y=4),需要额外判断索引有效性,避免越界:

x, y = 0, 0  # 左上角边缘位置
offsets = [(-1, 0), (1, 0), (0, -1), (0, 1)]
valid_neighbors = []
for dx, dy in offsets:
    nx, ny = x + dx, y + dy
    # 检查索引是否在数组范围内
    if 0 <= nx < a.shape[0] and 0 <= ny < a.shape[1]:
        valid_neighbors.append(a[nx, ny])
print(valid_neighbors)  # 输出:[48, 24](仅下方和右方有效)

内容的提问来源于stack exchange,提问作者skywave1980

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:25:33