首页 > 解决方案 > 如何计算数据集中所有点的多个欧几里得距离?

问题描述

我是 python 新手,我有一个包含数百个条目的数据集,我想找到每个点的第 6 个最近邻的欧几里德距离并保存它们。

条目是这样的:

362.240997 242.054993
505.821014 159.210007
420.803986 134.830002
504.035004 314.125000
356.670013 199.093994
326.545990 91.766998
214.477005 63.821999
351.351013 86.885002
216.041000 242.024994
441.700012 277.333008
68.678001 203.095001
547.051025 99.218002
405.983002 141.934006
402.239990 247.876007
197.134003 260.622009
163.141006 66.302002
561.950989 172.966995
340.036987 115.315002
63.076000 78.059998
261.072998 268.122009
319.376007 65.832001
.......

我不知道从哪里开始,我试图环顾四周,但什么都不懂,因为这太具体了。任何帮助表示赞赏。

非常感谢大家!

标签: python

解决方案


这是仅使用python的另一种方法。我只是使用熊猫来导入数据。因此,首先从您的数据中创建一个 csv :

import pandas

# Read your csv :
df = pd.read_csv('your_file.csv')

# Consider your points as tuples in a list
data = [(float(x),float(y)) for x, y in df[['x', 'y']].values ]

nearest_points = []
for point in data:
    # Compute the distance between the current point and all others
    distances = [math.sqrt((point[0]-x[0] )**2+ (point[1]-x[1])**2) for x in data]
    # Use np.argsort() to sort the array and keep the three closest points
    nearest_points.append([data[i] for i in np.argsort(distances)[1:4]])

推荐阅读