简体   繁体   English

有效地为数组赋值

[英]Assign values to array efficiently

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).我认为使用 numpy 库(没有循环)必须是一种有效的方法。

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.相对于您的代码,这种方式非常有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM