计算两个Pandas数据帧中行之间的欧几里得距离。

10

我有两个熊猫数据框 d1d2,它们看起来像这样:

d1 看起来像:

  output   value1   value2   value2
    1           100     103      87
    1           201     97.5     88.9
    1           144     54       85

d2 看起来像:

 output   value1   value2   value2
    0           100     103      87
    0           201     97.5     88.9
    0           144     54       85
    0           100     103      87
    0           201     97.5     88.9
    0           144     54       85

列输出在d1的所有行中具有值1,在d2的所有行中具有值0。它是一个分组变量。我需要找到d1和d2每一行之间的欧几里得距离(不是在d1或d2内部)。如果d1m行,d2n行,则距离矩阵将有m行和n列。

1个回答

20

通过使用scipy.spatial.distance.cdist

from scipy.spatial.distance import cdist

ary = cdist(d1.iloc[:,1:], d2.iloc[:,1:], metric='euclidean')

pd.DataFrame(ary)
Out[1274]: 
            0           1          2           3           4          5
0    0.000000  101.167485  65.886266    0.000000  101.167485  65.886266
1  101.167485    0.000000  71.808495  101.167485    0.000000  71.808495
2   65.886266   71.808495   0.000000   65.886266   71.808495   0.000000

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接