Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在大型numpy阵列上运行ndnumerate的更快方法_Python_Loops_Numpy - Fatal编程技术网

Python 在大型numpy阵列上运行ndnumerate的更快方法

Python 在大型numpy阵列上运行ndnumerate的更快方法,python,loops,numpy,Python,Loops,Numpy,嗨,我想加快我的计算速度,使用此ndnumerate循环非常慢: 下面的循环通过一个numpy数组,对每个单元格进行一些数学运算,但忽略-9999值,使它们保持不变 my_array = np.array([[-9999, 1, 1], [2, 2, -9999], [3, 3, 3]]) # Intialise two empty arrays 1_d = np.empty_like(my_array, dtype = float) 3_d

嗨,我想加快我的计算速度,使用此ndnumerate循环非常慢:

下面的循环通过一个numpy数组,对每个单元格进行一些数学运算,但忽略-9999值,使它们保持不变

my_array = np.array([[-9999, 1, 1],
             [2, 2, -9999],
             [3, 3, 3]])

# Intialise two empty arrays
1_d = np.empty_like(my_array, dtype = float)
3_d = np.empty_like(my_array, dtype = float)

start = time.time()

for [x, y], value in np.ndenumerate(my_array):
     if value >= 0:
         1_d[x, y] = value - (20 * (100 - value)) / ((100 - value) + math.exp(2.533 - 0.0636 * (100 - value)))

         3_d[x, y] = value * math.exp(0.00673 * (100 - value))
    else:
        1_d[x, y] = -9999
        3_d[x, y] = -9999

print "Calculating numbers took " + str(round(time.time() - start,2)) + "s.")

您不应该对循环执行此操作,而应该使用numpy数组的矢量化特性,因为在这种情况下这是完全可能的:

a1_d = my_array - (20 * (100 - my_array)) / ((100 - my_array) + np.exp(2.533 - 0.0636 * (100 - my_array)))
a3_d = my_array * np.exp(0.00673 * (100 - my_array))
要恢复-9999值,可以执行以下操作:

a1_d[my_array == -9999] = -9999
a3_d[my_array == -9999] = -9999
或者另一种选择是使用
np.nan
而不是-9999,它只会传播:

my_array = my_array.astype(float)
my_array[my_array == -9999] = np.nan
或者,另一个选项是在计算过程中执行布尔索引:

valid = (my_array != -9999)
a1_d[valid] = my_array[valid] * ...
a3_d[~valid] = -9999

对于这个小示例阵列,使用For循环(使用
%%timeit
)需要70µs而不是260µs。

您可以使用
屏蔽阵列

import numpy as np

my_array = np.array([[-9999, 1, 1],
             [2, 2, -9999],
             [3, 3, 3]])

value = np.ma.masked_values(my_array, -9999)
d1 = value - (20 * (100 - value)) / ((100 - value) + np.exp(2.533 - 0.0636 * (100 - value)))
d3 = value * np.exp(0.00673 * (100 - value))

非常感谢,我确实尝试过你提到的方式,我对numpy还是个新手,所以很难处理-9999值。