Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign values to array efficiently

Tags:

python

How I can do for do this code efficiently?

import numpy as np

array = np.zeros((10000,10000)) 
lower = 5000  
higher = 10000 
for x in range(lower, higher): 
    for y in range(lower, higher):
        array[x][y] = 1     
print(array)

I think must be a efficient way to do this with a numpy library (without loops).

like image 794
Chariot Avatar asked Sep 21 '19 12:09

Chariot


People also ask

How do you assign a value to an array of arrays?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

What happen if you assign value more than size in array?

If you try to access the array position (index) greater than its size, the program gets compiled successfully but, at the time of execution it generates an ArrayIndexOutOfBoundsException exception.

Is array more efficient than list?

Arrays can store data very compactly and are more efficient for storing large amounts of data. Arrays are great for numerical operations; lists cannot directly handle math operations. For example, you can divide each element of an array by the same number with just one line of code.


1 Answers

Try this :

array[lower:higher, lower:higher] = 1
# OR
array[lower:higher, lower:higher].fill(1) # Faster

As you're dwelling with huge array, the second process will be faster to the first one. Here is sample time check-up with low-scale data :

>>> from timeit import timeit as t
>>> t("""import numpy as np; a=np.zeros((100,100)); a[50:100,50:100].fill(1)""")
3.619488961998286
>>> t("""import numpy as np; a=np.zeros((100,100)); a[50:100,50:100] = 1""")
3.688145470998279
like image 92
Arkistarvh Kltzuonstev Avatar answered Sep 20 '22 19:09

Arkistarvh Kltzuonstev