在NumPy中更改数组边缘的值 [英] Changing values on the edges of an array in NumPy

查看:94
本文介绍了在NumPy中更改数组边缘的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

[[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]]

那是我的代码:

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?

推荐答案

方法1

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

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

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

方法2

另一种 short 方式-

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

方法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]])

这篇关于在NumPy中更改数组边缘的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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