Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 640
user541686 Avatar asked Apr 15 '12 02:04

user541686


People also ask

How do you make a 2D NumPy array of zeros?

Create two dimensional (2D) Numpy Array of zeros To create a multidimensional numpy array filled with zeros, we can pass a sequence of integers as the argument in zeros() function. For example, to create a 2D numpy array or matrix of 4 rows and 5 columns filled with zeros, pass (4, 5) as argument in the zeros function.

How do you create a 2-dimensional NumPy array?

Creating a Two-dimensional Array If you only use the arange function, it will output a one-dimensional array. To make it a two-dimensional array, chain its output with the reshape function. First, 20 integers will be created and then it will convert the array into a two-dimensional array with 4 rows and 5 columns.

How do you square each element in a NumPy array?

square(arr, out = None, ufunc 'square') : This mathematical function helps user to calculate square value of each element in the array. Parameters : arr : [array_like] Input array or object whose elements, we need to square.


1 Answers

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.]]
like image 187
Joe Kington Avatar answered Oct 08 '22 23:10

Joe Kington