6

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

0000000000000000000
0000000000000000000
0000000000111110000
0000000000111110000
0000000000111110000
0000000000000000000

即在特定范围内具有给定值的数组,否则为零?

4

1 回答 1

13

只需创建一个零数组并将您想要的区域设置为一个。

例如

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.]]
于 2012-04-15T03:04:27.600 回答