在Python中,如何获取numpy数组周围的值?
我有一个2d numpy数组,但我只希望边界周围的值作为列表,就像在框的周长周围走动一样 为了举例说明,对于二维数组,我想从一个角开始,然后获取框中所有的值 结果是这样的。。。在Python中,如何获取numpy数组周围的值?,python,numpy,Python,Numpy,我有一个2d numpy数组,但我只希望边界周围的值作为列表,就像在框的周长周围走动一样 为了举例说明,对于二维数组,我想从一个角开始,然后获取框中所有的值 结果是这样的。。。 给定一个名为数组的2d数组 import numpy as np x, y = np.meshgrid(range(1,6), range(5)) array=x*y array[0,0]=999 …看起来是这样的: array([[999, 0, 0, 0, 0], [ 1, 2
给定一个名为
数组的2d数组
import numpy as np
x, y = np.meshgrid(range(1,6), range(5))
array=x*y
array[0,0]=999
…看起来是这样的:
array([[999, 0, 0, 0, 0],
[ 1, 2, 3, 4, 5],
[ 2, 4, 6, 8, 10],
[ 3, 6, 9, 12, 15],
[ 4, 8, 12, 16, 20]])
我们可以通过仔细的切片得到边界附近的值
border = []
border += list(array[0, :-1]) # Top row (left to right), not the last element.
border += list(array[:-1, -1]) # Right column (top to bottom), not the last element.
border += list(array[-1, :0:-1]) # Bottom row (right to left), not the last element.
border += list(array[::-1, 0]) # Left column (bottom to top), all elements element.
注意:我们不想重复计算拐角。这就是为什么我们不在每个行/列切片中包含最后一个元素的原因。但是,在最后一条语句中,我们包含了关闭路径的最后一个元素
边框的值
:
array([999, 0, 0, 0, 0, 5, 10, 15, 20, 16, 12, 8, 4,
3, 2, 1, 999])
我将其转换为一个函数,允许您指定从哪个角开始,并逆时针或顺时针绕阵列行走()给定一个名为阵列的二维阵列
import numpy as np
x, y = np.meshgrid(range(1,6), range(5))
array=x*y
array[0,0]=999
…看起来是这样的:
array([[999, 0, 0, 0, 0],
[ 1, 2, 3, 4, 5],
[ 2, 4, 6, 8, 10],
[ 3, 6, 9, 12, 15],
[ 4, 8, 12, 16, 20]])
我们可以通过仔细的切片得到边界附近的值
border = []
border += list(array[0, :-1]) # Top row (left to right), not the last element.
border += list(array[:-1, -1]) # Right column (top to bottom), not the last element.
border += list(array[-1, :0:-1]) # Bottom row (right to left), not the last element.
border += list(array[::-1, 0]) # Left column (bottom to top), all elements element.
注意:我们不想重复计算拐角。这就是为什么我们不在每个行/列切片中包含最后一个元素的原因。但是,在最后一条语句中,我们包含了关闭路径的最后一个元素
边框的值
:
array([999, 0, 0, 0, 0, 5, 10, 15, 20, 16, 12, 8, 4,
3, 2, 1, 999])
我将其转换为一个函数,允许您指定从哪个角开始,并逆时针或顺时针绕阵列行走()