在NumPy中更改数组边缘的值

Hen*_*rra 3 python arrays numpy

我仅使用NumPy工具创建一个数组。那里是:

[[2 2 2 2 2]
 [2 1 1 1 2]
 [2 1 1 1 2]
 [2 1 1 1 2]
 [2 2 2 2 2]]
Run Code Online (Sandbox Code Playgroud)

那是我的代码:

import numpy as np
x = np.ones((5, 5), dtype = int)
x[0, :] = 2
x[4, :] = 2
x[:, 0] = 2
x[:, 4] = 2
print(x)
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以以更简单(更短)的方式创建这样的数组?

Isr*_*ebe 6

import numpy as np

a = np.ones((5, 5))
b = np.pad(a[1:-1,1:-1], pad_width=((1, 1), (1, 1)), mode='constant', 
constant_values=2)
print b
Run Code Online (Sandbox Code Playgroud)


Div*_*kar 5

方法1

初始化为2s(边值)并1s在中间部分分配-

x = 2*np.ones((5, 5), dtype = int)
x[1:-1,1:-1] = 1
Run Code Online (Sandbox Code Playgroud)

方法#2

另一种短途 -

x = np.ones((5, 5), dtype = int)
x[:,[0,-1]] = x[[0,-1]] = 2
Run Code Online (Sandbox Code Playgroud)

方法3

一线2D卷积-

In [302]: from scipy.signal import convolve2d

In [303]: (convolve2d(np.ones((5,5)), np.ones((3,3)),'same')<9)+1
Out[303]: 
array([[2, 2, 2, 2, 2],
       [2, 1, 1, 1, 2],
       [2, 1, 1, 1, 2],
       [2, 1, 1, 1, 2],
       [2, 2, 2, 2, 2]])
Run Code Online (Sandbox Code Playgroud)