[英]Faster way running ndnumerate on large numpy array
Hi I want speed up my calculation which is very slow using this ndnumerate loop: 嗨,我希望加快我的计算,使用这个ndnumerate循环非常慢:
The loop below goes through a numpy array and carrys out some math on each cell but ignores the -9999 values, keeping them the same. 下面的循环通过一个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.")
You shouldn't do this with a loop, but just use the vectorized nature of numpy arrays, as this is perfectly possible in this case: 你不应该用循环来做这个,而只是使用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))
To have the -9999 values back, you can do: 要恢复-9999值,您可以执行以下操作:
a1_d[my_array == -9999] = -9999
a3_d[my_array == -9999] = -9999
or another option would be to use np.nan
instead of -9999, which would just propagate: 或者另一种选择是使用np.nan
而不是-9999,这只会传播:
my_array = my_array.astype(float)
my_array[my_array == -9999] = np.nan
or another option would be to do boolean indexing during the calculation: 或另一种选择是在计算过程中进行布尔索引:
valid = (my_array != -9999)
a1_d[valid] = my_array[valid] * ...
a3_d[~valid] = -9999
For this small example array, this takes ca 70 µs instead of 260 µs with the for loop (using %%timeit
) 对于这个小示例阵列,使用for循环需要大约70μs而不是%%timeit
(使用%%timeit
)
You can use masked array
: 你可以使用masked array
:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.