两个数据帧中每条记录之间的最近记录和对应距离



>假设我有两个DataFrame s:XAXB,例如每个有3行和2列:

import pandas as pd
XA = pd.DataFrame({
    'x1': [1, 2, 3],
    'x2': [4, 5, 6]
})
XB = pd.DataFrame({
    'x1': [8, 7, 6],
    'x2': [5, 4, 3]
})

对于XA中的每个记录,我想找到最近的记录(例如基于欧几里得距离XB(,以及相应的距离。例如,这可能会返回一个在 id_A 上索引的DataFrame,以及 id_Bdistance 的列。

如何才能最有效地做到这一点?

一种方法

是计算全距离矩阵,然后melt它并使用 nsmallest 进行聚合,这将返回索引和值:

from scipy.spatial.distance import cdist
def nearest_record(XA, XB):
    """Get the nearest record in XA for each record in XB.
    Args:
        XA: DataFrame. Each record is matched against the nearest in XB.
        XB: DataFrame.
    Returns:
        DataFrame with columns for id_A (from XA), id_B (from XB), and dist.
        Each id_A maps to a single id_B, which is the nearest record from XB.
    """
    dist = pd.DataFrame(cdist(XA, XB)).reset_index().melt('index')
    dist.columns = ['id_A', 'id_B', 'dist']
    # id_B is sometimes returned as an object.
    dist['id_B'] = dist.id_B.astype(int)
    dist.reset_index(drop=True, inplace=True)
    nearest = dist.groupby('id_A').dist.nsmallest(1).reset_index()
    return nearest.set_index('level_1').join(dist.id_B).reset_index(drop=True)

这表明id_B 2 是 XA 中三条记录中每条记录中最接近的记录:

nearest_record(XA, XB)
 id_A       dist id_B
0   0   5.099020    2
1   1   4.472136    2
2   2   4.242641    2

但是,由于这涉及计算全距离矩阵,因此当XAXB很大时,它会很慢或失败。计算每行最接近值的替代方法可能会更快。

修改此答案以避免全距离矩阵,您可以在XA中找到每行最近的记录和距离(nearest_record1()(,然后调用apply在每一行(nearest_record()(上运行它。这将测试中的运行时间缩短 ~85%。

from scipy.spatial.distance import cdist
def nearest_record1(XA1, XB):
    """Get the nearest record between XA1 and XB.
    Args:
        XA: Series.
        XB: DataFrame.
    Returns:
        DataFrame with columns for id_B (from XB) and dist.
    """
    dist = cdist(XA1.values.reshape(1, -1), XB)[0]
    return pd.Series({'dist': np.amin(dist), 'id_B': np.argmin(dist)})
def nearest_record(XA, XB):
    """Get the nearest record in XA for each record in XB.
    Args:
        XA: DataFrame. Each record is matched against the nearest in XB.
        XB: DataFrame.
    Returns:
        DataFrame with columns for id_A (from XA), id_B (from XB), and dist.
        Each id_A maps to a single id_B, which is the nearest record from XB.
    """
    res = XA.apply(lambda x: nearest_record1(x, XB), axis=1)
    res['id_A'] = XA.index
    # id_B is sometimes returned as an object.
    res['id_B'] = res.id_B.astype(int)
    # Reorder columns.
    return res[['id_A', 'id_B', 'dist']]

这也返回正确的结果:

nearest_record(XA, XB)
    id_A    id_B        dist
0      0       2    5.099020
1      1       2    4.472136
2      2       2    4.242641

相关内容

  • 没有找到相关文章

最新更新