【发布时间】:2013-05-20 13:17:23
【问题描述】:
我想将一维数组中的值从不规则网格插入到规则网格。例如,假设原始数据在不规则间隔的 X 坐标处具有值:
source_x = np.asarray([127.3, 759.4, 1239.1, ..., 98430.1])
source_y = whatever(x) # No really a function but a set of masurements
目标网格也是一维的,但 X 坐标沿轴有规律地分布:
dest_x = np.arange(250, 100000, 500)
我想为目标dest_xcoordinates 数组的每个点找到原始source_xcoordinates 数组中两个最近元素的距离和索引。例如:
dest_x[0] = 250
indices = [0, 1]
distances = [250-127.3, 759.4-250]
如果可能,这应该作为原子操作来完成。
我的第一个想法是使用scipy.spatial.KDTree,但这不允许一维数据。还有其他选择吗?
编辑
有一个“丑陋”选项涉及一个“虚拟”零坐标,它允许使用scipy.spatial.KDTree:
source_x = np.asarray([127.3, 759.4, 1239.1, ..., 98430.1])
source_dummy = np.zeros_like(source_x)
dest_x = np.arange(250, 100000, 500)
dest_dummy = np.zeros_like(dest_x)
src = np.vstack((source_x, source_dummy)).T
dst = np.vstack((dest_x, dest_dummy)).T
tree = KDTree(src)
distances, indices = tree.query(dst, 2)
但是,我不太喜欢这种方法...
【问题讨论】:
-
对于线性插值,只需使用
numpy.interp()。如果您需要索引本身,请使用numpy.searchsorted()。唯一棘手的一点是处理超出数据范围的网格值。有了索引后,距离很容易计算。 -
感谢您的回答,
numpy.searchsorted是查找一维数组中索引的好方法,并且之前也很容易计算权重(距离)。 -
@RobertKern 您的评论就是答案!您可以将其发布为官方答案,以便人们可以更快地找到它...