我目前正在尝试使用Python内插大量X和Y值。数组很长(600万个值),我正在尝试将其扩展到1000万个值。鉴于我的问题,插值不应超过Y的最小值/最大值。为此,我编写了一个函数来执行距离反比加权(IDW)插值。但是,它花费的时间太长(至少10天)才能完成。我使用IDW是因为数据也有点嘈杂,并且通过将p值设置为<1.0可以有效地使其平滑。这是我写的函数:
def idw_simple(x, y, x_new, p):
# interpolate 2D data using inverse distance weighted technique
y_new = np.array([])
for i in x_new:
# Calc. distance for each x_new-value from every x-value
min_array = np.abs(x - i)
min_array_sorted = np.sort(min_array)
# Find 10 closest x-values
near_indices = [int(np.where(min_array == k)[0]) for k in min_array_sorted[:10]]
# Calc. y_new based on nearby weighted points
near_indices = np.sort(near_indices)
weights = 1 / (min_array[near_indices] ** p)
y_new = np.append(y_new, np.sum(weights * y[near_indices]) / weights.sum())
return y_new
[如果有人对如何加快速度有想法,或者您认为还有另一种插值技术会提供相似的结果,我很想听听人们的想法。
如果输入数据以x
的升序排序,则可以更有效地执行“ 10个最近的点”步骤多。在循环初始化j = 0
之前,然后在i
循环主体的顶部执行
while j < len(x) - 10 and abs(x[j+10] - i) < abs(x[j] - i):
j = j + 1
然后x[j:j+10]
和y[j:j+10]
将是每个循环迭代中最接近i
的10个点,没有每次都需要排序和过滤1000万个元素列表。这应该快很多倍。