在NumPy中更改数组边缘的值

时间:2021-06-06 21:20:12

I am to create an array using only NumPy tools. There it is:

我只使用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]]

That is my code:

那是我的代码:

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)

I wonder if it is possible to create an array like this in an easier (shorter) way?

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

3 个解决方案

#1


4  

Approach #1

方法#1

Initialize with 2s (edge values) and assign 1s in middle portion -

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

x = 2*np.ones((5, 5), dtype = int)
x[1:-1,1:-1] = 1

Approach #2

方法#2

Another short way -

另一个简短方法 -

x = np.ones((5, 5), dtype = int)
x[:,[0,-1]] = x[[0,-1]] = 2

Approach #3

方法#3

One-liner with 2D convolution -

带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]])

#2


2  

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

#3


1  

x = numpy.full((5,5), 2, dtype=int)
x[1:-1,1:-1] = 1

#1


4  

Approach #1

方法#1

Initialize with 2s (edge values) and assign 1s in middle portion -

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

x = 2*np.ones((5, 5), dtype = int)
x[1:-1,1:-1] = 1

Approach #2

方法#2

Another short way -

另一个简短方法 -

x = np.ones((5, 5), dtype = int)
x[:,[0,-1]] = x[[0,-1]] = 2

Approach #3

方法#3

One-liner with 2D convolution -

带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]])

#2


2  

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

#3


1  

x = numpy.full((5,5), 2, dtype=int)
x[1:-1,1:-1] = 1