我试图将数组中的条件值插入到精确位置的空数组中。
empty_array = np.zeros([40,100])
for x in range (1,24):
array[x,:,:] #which is also sized 40x100
if the_values_in_the_array < 0.25:
the_values_in_the_array = 0
empty_array = empty_array + array [x,:,:]
我应该将哪种语法用于此逻辑?我应该如何扫描the_values_in_the_array以找到条件值?
答案 0 :(得分:4)
empty_array = np.zeros([40,100])
array = np.random.rand(24,40,100)
array[array<0.25]=0 # change all the values which is <0.25 to 0
for x in range(1,24):
empty_array += array[x,:,:]
答案 1 :(得分:1)
我认为这是你要做的操作。我建议使用np.where
例程将小于0.25的值设置为零。然后,您可以只计算数组的第一个维度,以获得您正在寻找的输出数组。我减少了示例中问题的维度。
import numpy as np
vals = np.random.random([24, 2, 3])
vals_filtered = np.where(vals < 0.25, 0.0, vals)
out = vals_filtered.sum(axis=0)
print("First sample array has the slice vals[0,:,:]:\n{}\n".format(vals[0, :, :]))
print("First sample array with vals>0.25 set to 0.0:\n{}\n".format(vals_filtered[0, :, :]))
print("Output array is the sum over the first dimension:\n{}\n".format(out))
返回以下输出。
First sample array has the slice vals[0, :, :]:
[[ 0.16272567 0.13695067 0.5954866 ]
[ 0.50367823 0.8519252 0.3000367 ]]
First sample array with vals>0.25 set to 0.0:
[[ 0. 0. 0.5954866 ]
[ 0.50367823 0.8519252 0.3000367 ]]
Output array is the sum over the first dimension:
[[ 11.12707813 12.04175706 11.5812803 ]
[ 13.73036272 9.3988165 12.41808745]]
这是您要找的计算吗?调用vals.sum(axis=0)
是一种更快速的操作方式。调用numpy的内置数组例程通常更好,而不是显式的for
循环。