脾气暴躁的邻居总是作为3x3矩阵 [英] Numpy get neighbors always as 3x3 matrix

查看:64
本文介绍了脾气暴躁的邻居总是作为3x3矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个大小为(5,5)的2d numpy数组.我可以使用以下语句获取索引(i,j)的邻居:

Let's say I have a 2d numpy array of the size (5,5). I can get the neighbors of the index (i,j) with the following statement:

a = range(25)
a = np.reshape(a, (5,5))

n = a[i-1:i+2, j-1:j+2]

对于 0<i,j<4 .我的问题是我一直想得到一个 3x3 数组,但是如果索引之一是0或4,我就不会得到它(如果 i = 0 的范围是(-1,2)=(4,2),我们得到一个空范围)

That works great for 0 < i,j < 4. My problem is that I always want to get a 3x3 array but if one of the indices is 0 or 4 I do not get it (in case i=0 the range is (-1, 2) = (4, 2) and we get an empty range)

您有什么主意,我怎样才能始终获得一个 3x3 矩阵并用零填充失败的索引"?

Do you have any ideas how I can always get a 3x3 matrix and fill the "failed indices" with zeros?

推荐答案

使用 np.pad 首先扩展数组,然后将其索引到结果中.您必须相应地改变索引.

Use np.pad to extend your array first and index into the result instead. You'll have to shift your indices accordingly.

>>> b = np.pad(a, pad_width=1, mode='constant')
>>> b
array([[ 0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  1,  2,  3,  4,  0],
       [ 0,  5,  6,  7,  8,  9,  0],
       [ 0, 10, 11, 12, 13, 14,  0],
       [ 0, 15, 16, 17, 18, 19,  0],
       [ 0, 20, 21, 22, 23, 24,  0],
       [ 0,  0,  0,  0,  0,  0,  0]])
>>>

这篇关于脾气暴躁的邻居总是作为3x3矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆