python - 两个数组的高效匹配(KDTree的使用方法)

标签 python numpy pandas scipy kdtree

我有两个二维数组,obs1obs2。它们代表两个独立的测量系列,并且都有 dim0 = 2,并且 dim1 略有不同,比如 obs1.shape = (2, 250000) , 和 obs2.shape = (2, 250050)obs1[0]obs2[0]表示时间,obs1[1]obs2[1]表示一些空间坐标。两个数组(或多或少)都按时间排序。两个测量系列之间的时间和坐标应该相同,但实际上并非如此。此外,并非 obs1 中的每个测量值在 obs2 中都有相应的值,反之亦然。另一个问题是时间可能会有轻微的偏移。

我正在寻找一种有效的算法来将 obs2 中的最佳匹配值关联到 obs1 中的每个测量值。目前,我是这样做的:

define dt = some_maximum_time_difference
define dx = 3
j = 0
i = 0
matchresults = np.empty(obs1.shape[1])
for j in obs1.shape[1]:
    while obs1[0, j] - obs2[0, j] < dt:
        i += 1
    matchresults[j] = i - dx + argmin(abs(obs1[1, i] - obs2[1, i-dx:i+dx+1]))

这会产生很好的结果。但是,它非常慢,在循环中运行。

我将非常感谢有关如何提高此算法速度的想法,例如使用 KDtree 或类似的东西。

最佳答案

在这种情况下使用 cKDTree 看起来像:

from scipy.spatial import cKDTree

obs2 = array with shape (2, m)
obs1 = array with shape (2, n)

kdt = cKDTree(obs2.T)
dist, indices = kdt.query(obs1.T)

其中 indices 将包含 obs2 中的列索引,对应于 obs1 中的每个观察值。请注意,我必须转置 obs1obs2

关于python - 两个数组的高效匹配(KDTree的使用方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15525493/

相关文章:

python pandas-可以使用where(max())比较相同形状的3个dfs?这是一个掩蔽问题吗?

python - 如何绘制不同长度的数组

python - 将 'now' 时间戳列添加到 pandas df

python - 相当于 numpy.roll 的 Pandas

python - 用值填充非常大的数据框的快速方法

python - 如果满足特定条件如何删除行(Python)

python - 如何处理 lambda 表达式中的正则表达式和空值?

python - 同时渲染模板和 send_from_directory

python - Django 不需要 ContentType

Python Itertools 仅排列字母和数字