计算两个 pandas 数据框的行之间的欧几里得距离 [英] Compute Euclidean distance between rows of two pandas dataframes

查看:163
本文介绍了计算两个 pandas 数据框的行之间的欧几里得距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个大熊猫数据帧d1d2像这样:

I have two pandas dataframes d1 and d2 that look like these:

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内).如果d1具有m行,而d2具有n行,则距离矩阵将具有m行和n列

The column output has a value of 1 for all rows in d1 and 0 for all rows in d2. It's a grouping variable. I need to find euclidean distance between each rows of d1 and d2 (not within d1 or d2). If d1 has m rows and d2 has n rows, then the distance matrix will have m rows and n columns

推荐答案

通过使用scipy.spatial.distance.cdist:

import scipy

ary = scipy.spatial.distance.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

这篇关于计算两个 pandas 数据框的行之间的欧几里得距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆