Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize 2D numpy array

Tags:

python

numpy

Note: I found the answer and answered my own question, but I have to wait 2 days to accept my answer.


How do I initialize a numpy array of size 800 by 800 with other values besides zero? :

array = numpy.zeros((800, 800))

I am looking for a solution like this, where I could pass in a list (or lists) of values.

 array = numpy.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

Edit: I do not want to fill it with identical values.

I wanted a quick code example that demonstrates how this works without a long detailed example like I find in the other questions. I also want something simple to understand like converting a python array into a numpy array. I also am looking for the specific case of a 2D array.

like image 546
Rock Lee Avatar asked Jan 09 '23 07:01

Rock Lee


2 Answers

You can use fill method to init the array.

x = np.empty(shape=(800,800))
x.fill(1)
like image 160
Wang Hui Avatar answered Jan 14 '23 16:01

Wang Hui


Found out the answer myself: This code does what I want, and shows that I can put a python array ("a") and have it turn into a numpy array. For my code that draws it to a window, it drew it upside down, which is why I added the last line of code.

# generate grid
    a = [ ]
    allZeroes = []
    allOnes = []

    for i in range(0,800):
        allZeroes.append(0)
        allOnes.append(1)

    # append 400 rows of 800 zeroes per row.
    for i in range(0, 400):
        a.append(allZeroes)

    # append 400 rows of 800 ones per row.
    for i in range(0,400):
        a.append(allOnes)


#So this is a 2D 800 x 800 array of zeros on the top half, ones on the bottom half.
array = numpy.array(a)

# Need to flip the array so my other code that draws 
# this array will draw it right-side up
array = numpy.flipud(array)
like image 22
Rock Lee Avatar answered Jan 14 '23 16:01

Rock Lee