5

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

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

2

you can use below code:

array[5000:10000,5000:10000].fill(1)

this way is very efficient relative to your code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.