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).
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
you can use below code:
array[5000:10000,5000:10000].fill(1)
this way is very efficient relative to your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.