Search code examples
pythonarraysnumpyrect

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

i.e. an array which has a given value inside certain bounds, or zero otherwise?


Solution

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

    E.g.

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