如何在numpy中创建一个2D“rect”数组(1的方块,否则为0)?

时间:2012-04-15 02:57:38

标签: python arrays numpy rect

创建2D numpy“rect”数组的“正确”方法是什么,如:

0000000000000000000
0000000000000000000
0000000000111110000
0000000000111110000
0000000000111110000
0000000000000000000

即。一个在某些边界内具有给定值的数组,否则为零?

1 个答案:

答案 0 :(得分:11)

只需创建一个零数组并将所需区域设置为一个。

E.g。

import numpy as np
data = np.zeros((6,18))
data[2:5, 9:14] = 1
print data

这会产生:

[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  1.  1.  1.  1.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  1.  1.  1.  1.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  1.  1.  1.  1.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]