[英]Indexing numpy 2D array that wraps around
你如何索引一个在超出边界时环绕的 numpy 数组?
例如,我有 3x3 数组:
import numpy as np
matrix = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])
##
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]]
假设我想索引值15
所在的索引 (2,4) 周围的值。 我想用值取回数组:
[[9, 10, 6]
[14, 15, 11]
[4, 5, 1]]
基本上所有 15 左右的值都被返回,假设它环绕
在numpy
数组中查找相邻元素的一个相当标准的习惯用法是arr[x-1:x+2, y-1:y+2]
。 但是,由于您想要换行,您可以使用换行模式填充数组,并偏移x
和y
坐标以考虑此填充。
此答案假定您想要所需元素第一次出现的邻居。
首先,找到元素的索引和偏移量以考虑填充:
x, y = np.unravel_index((m==15).argmax(), m.shape)
x += 1; y += 1
现在pad
,并索引您的数组以获取您的邻居:
t = np.pad(m, 1, mode='wrap')
out = t[x-1:x+2, y-1:y+2]
array([[ 9, 10, 6],
[14, 15, 11],
[ 4, 5, 1]])
这是您无需填充即可完成的操作。 这可以很容易地推广到当您想要多个邻居并且没有填充数组的开销时。
def get_wrapped(matrix, i, j):
m, n = matrix.shape
rows = [(i-1) % m, i, (i+1) % m]
cols = [(j-1) % n, j, (j+1) % n]
return matrix[rows][:, cols]
res = get_wrapped(matrix, 2, 4)
让我解释一下这里发生了什么return matrix[rows][:, cols]
。 这真的是两个操作。
第一个是matrix[rows]
,它是matrix[rows, :]
简写matrix[rows, :]
这意味着给我选定的行,以及这些行的所有列。
然后接下来我们做[:, cols]
这意味着给我所有的行和选定的 cols。
take
函数就地工作。
>>> a = np.arange(1, 16).reshape(3,5)
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]])
>>> b = np.take(a, [3,4,5], axis=1, mode='wrap')
array([[ 4, 5, 1],
[ 9, 10, 6],
[14, 15, 11]])
>>> np.take(b, [1,2,3], mode='wrap', axis=0)
array([[ 9, 10, 6],
[14, 15, 11],
[ 4, 5, 1]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.