欧氏距离的python数据帧矩阵

标签 python pandas dataframe

我想创建一个自己定制的 k 最近邻方法。

为此,我需要一个矩阵 (x : y),它返回给定函数的 x 和 y 的每个组合的距离(例如,基于我的数据集的 7 项的欧几里得)。

例如

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

如果我选择 x1 和 x2 以及 euclidean,那么输出应该是 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

等等……

如何在不遍历数据框的情况下编写它?

在此先感谢您的支持。

最佳答案

您可以使用 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))

如果您只想将数组作为输出,而不是 DataFrame,只需使用 squareform 本身,而不用将其包装在 DataFrame 中。

结果输出(作为 DataFrame):

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

关于欧氏距离的python数据帧矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40871186/

相关文章:

python - 删除最小化和最大化按钮

r - 从 R 中的数据框中获取具有多个单独观察的组级观察计数

python - 从数组的元素中查找所有匹配的单词,保留这些单词,但删除不包含这些单词的元素

python - pandas 的元素二进制 bool 操作数具有相同长度元素持有不同索引的规则是什么?

python - 来自 Pandas DataFrame 的用户定义的 Json 格式

python - cx_Oracle中如何使用Pandas Write_Frame将结果导出到Oracle数据库

python - DataFrame float 到整数?

从函数返回数据帧

python验证码解码器库

python - 模数符号在这里起什么作用?