2

I want to interpolate values in a 1D array from an irregular grid to a regular grid. For example, imagine that the original data has values at irregularly spaced X coordinates:

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

The destination grid is also 1D, but the X coordinates are regularly spaced along the axis:

dest_x = np.arange(250, 100000, 500)

I want to find the distance and index of the two closest elements in the original source_xcoordinates array for every point the destination dest_xcoordinates array. For example:

dest_x[0] = 250
indices = [0, 1]
distances = [250-127.3, 759.4-250]

This should be done as an atomic operation if possible.

My first idea was to use scipy.spatial.KDTree, but this doesn't allow 1D data. Any other options?

EDIT

There is an "ugly" option that involves a "dummy" coordinate of zeros, which allows using 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)

However, I don't like this approach that much...

4

1 回答 1

2

对于线性插值,只需使用numpy.interp(). 如果您需要索引本身,请使用numpy.searchsorted(). 唯一棘手的一点是处理超出数据范围的网格值。一旦有了索引,距离就很容易计算。

于 2013-06-03T14:23:09.227 回答