1 回答
TA贡献1863条经验 获得超2个赞
如果可以使间隔不重叠,那么您可以使用这样的函数:
import numpy as np
def func(data_array, intervals):
data_array = np.asarray(data_array)
start, end = np.asarray(intervals).T
data_array_exp = data_array[..., np.newaxis]
mask = (data_array_exp >= start) & (data_array_exp <= end)
return np.sum((data_array_exp + end) * mask * 100, axis=-1)
在这种情况下,结果应该与原始代码相同:
import numpy as np
def func_orig(data_array, intervals):
init = np.zeros((data_array.shape[0], data_array.shape[1]))
result_array = np.ma.masked_where((init == 0), init)
for inter in intervals:
start_inter = inter[0]
end_inter = inter[1]
mask_init = np.ma.masked_where((data_array > end_inter), data_array)
masked_array = np.ma.masked_where((mask_init < start_inter), mask_init)
outcome = (masked_array + end_inter) * 100
result_array[result_array.mask] = outcome[result_array.mask]
return result_array.data
data_array = np.array([[1, 1, 1], [1, 1, 2], [2, 2, 2], [3, 3, 3], [4, 4, 4]], np.int16)
intervals = [[1, 1.9], [2, 2.9], [3, 4]]
print(np.allclose(func(data_array, intervals), func_orig(data_array, intervals)))
# True
添加回答
举报