在Python中,如何获取numpy数组周围的值?

2024-03-29 14:46:46 发布

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

我有一个2d numpy数组,但我只希望边界周围的值作为列表,就像在框的周长周围走动一样

为了举例说明,对于二维数组,我想从一个角开始,然后获取框中所有的值

enter image description here

结果是这样的。。。 enter image description here


Tags: numpy列表数组边界周长
1条回答
网友
1楼 · 发布于 2024-03-29 14:46:46

给定一个名为array的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.

注意:我们不想重复计算拐角。这就是为什么我们不在每个行/列切片中包含最后一个元素的原因。但是,在最后一条语句中,我们包含了关闭路径的最后一个元素

border的值:

array([999,   0,   0,   0,   0,   5,  10,  15,  20,  16,  12,   8,   4,
         3,   2,   1, 999])

我将其转换为一个函数,允许您指定从哪个角开始,并逆时针或顺时针(https://gist.github.com/blaylockbk/a70537b41050d1d761ab6c5ab6e4bd43)绕数组走

相关问题 更多 >