简体   繁体   中英

How to create a 2D “rect” array (square block of 1's, else 0's) in numpy?

What is the "correct" way of creating a 2D numpy "rect" array, like:

0000000000000000000
0000000000000000000
0000000000111110000
0000000000111110000
0000000000111110000
0000000000000000000

ie an array which has a given value inside certain bounds, or zero otherwise?

Just create an array of zeros and set the area you want to one.

Eg

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

This yields:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM