2016-11-29 59 views
0

我想创建一个自己定制的k最近邻居方法。为此,我需要一个矩阵(x:y),它返回给定函数(例如基于我的数据集的7个项目的欧几里得)的x和y的每个组合的距离。欧几里得距离的python数据帧矩阵

例如

data: 
    x1 x2 x3 
    row 1: 1 2 3 
    row 2: 1 1 1 
    row 3: 4 2 3 

如果我选择X1和X2和欧几里得,那么输出应该是一个3x3输出

1:1=0 
1:2 =sqrt((1-1)^2+(2-1)^2)=1 
1:3 =sqrt((1-4)^2+(2-2)^2)=sqrt(3) 
2:1=1:2=1 
2:2=0 
2:3=sqrt((1-4)^2+(1-2)^2)=2 
3:3=0 

等等...

怎么写,没有通过数据帧进行迭代?

在此先感谢您的支持。

+0

它看起来像您的一些例子的计算是错误的,即'1:3'应该是'SQRT(9)= 3',和'2 :3'应该是'sqrt(10)'。 – root

回答

2

您可以使用scipy.spatial.distance.pdistscipy.spatial.distance.squareform

from scipy.spatial.distance import pdist, squareform 

dist = pdist(df[['x1', 'x2']], 'euclidean') 
df_dist = pd.DataFrame(squareform(dist)) 

如果你只是想一个数组作为输出,而不是一个数据帧,只使用squareform本身,而无需在数据帧加以包装。

所产生的输出(作为数据帧):

 0   1   2 
0 0.0 1.000000 3.000000 
1 1.0 0.000000 3.162278 
2 3.0 3.162278 0.000000 
+0

非常好!非常感谢! –

相关问题