Python 如何在数据阵列中找到单元格的邻居?
我正在使用Python中的n维数组,我希望根据给定单元格的坐标找到其“邻居”(相邻单元格)。问题是我事先不知道维度的数量 我试图按照的建议使用,但似乎不清楚如何将此方法应用于多个维度Python 如何在数据阵列中找到单元格的邻居?,python,arrays,numpy,multidimensional-array,scipy,Python,Arrays,Numpy,Multidimensional Array,Scipy,我正在使用Python中的n维数组,我希望根据给定单元格的坐标找到其“邻居”(相邻单元格)。问题是我事先不知道维度的数量 我试图按照的建议使用,但似乎不清楚如何将此方法应用于多个维度 请给我指出正确的方向。我假设你有一个(ndims,)索引向量,指定一些点p,你需要一个(m,ndims)索引数组,对应于数组中每个相邻元素(包括对角相邻元素)的位置 从索引向量p开始,您希望通过-1、0和+1的每个可能组合来偏移每个元素。这可以通过使用生成偏移量的(m,ndims)数组,然后将这些偏移量添加到p 您
请给我指出正确的方向。我假设你有一个
(ndims,)
索引向量,指定一些点p
,你需要一个(m,ndims)
索引数组,对应于数组中每个相邻元素(包括对角相邻元素)的位置
从索引向量p
开始,您希望通过-1、0和+1的每个可能组合来偏移每个元素。这可以通过使用生成偏移量的(m,ndims)
数组,然后将这些偏移量添加到p
您可能希望排除点p
本身(即offset==np.array([0,0,…,0])
,并且您可能还需要排除越界索引
import numpy as np
def get_neighbours(p, exclude_p=True, shape=None):
ndim = len(p)
# generate an (m, ndims) array containing all strings over the alphabet {0, 1, 2}:
offset_idx = np.indices((3,) * ndim).reshape(ndim, -1).T
# use these to index into np.array([-1, 0, 1]) to get offsets
offsets = np.r_[-1, 0, 1].take(offset_idx)
# optional: exclude offsets of 0, 0, ..., 0 (i.e. p itself)
if exclude_p:
offsets = offsets[np.any(offsets, 1)]
neighbours = p + offsets # apply offsets to p
# optional: exclude out-of-bounds indices
if shape is not None:
valid = np.all((neighbours < np.array(shape)) & (neighbours >= 0), axis=1)
neighbours = neighbours[valid]
return neighbours
这将推广到任何维度
如果您只想为
p
的“邻域”编制索引,而不想排除p
本身,那么一个更简单、更快的选择是使用slice
对象的元组:
idx = tuple(slice(pp - 1, pp + 2) for pp in p)
print(x[idx])
# [[1 1]
# [1 2]
# [1 1]]
myarray.shape
保存有关array@yurib我知道这一点,我的意思是我不能将实现建立在一定数量的维度上。
idx = tuple(slice(pp - 1, pp + 2) for pp in p)
print(x[idx])
# [[1 1]
# [1 2]
# [1 1]]