如何用Python基于欧氏距离查找DataFrame中距离指定ID最近的观测点
实现方案
依赖安装
如果还没安装所需依赖,执行以下命令安装:
pip install pandas numpy
完整可运行代码
import pandas as pd import numpy as np # 1. 加载数据:此处为示例数据构造逻辑,实际使用可替换为读取你的数据文件 # 例如读取csv:df = pd.read_csv("你的数据文件路径.csv") df = pd.DataFrame([ [12, 0.355, 0.362], [24, 0.577, 0.425], [15, 0.257, 0.486], [6, 0.585, 0.254], [34, 0.367, 0.533] ], columns=["ID", "PC1", "PC2"]) # 2. 定义要查询的目标ID target_id = 15 # 3. 逻辑处理 if target_id not in df["ID"].values: print(f"错误:ID {target_id} 不存在于数据集中") else: # 提取目标ID对应的PC1、PC2数值 target_pc1, target_pc2 = df.loc[df["ID"] == target_id, ["PC1", "PC2"]].iloc[0] # 向量化计算所有样本与目标点的欧氏距离 df["Distance"] = np.sqrt( (df["PC1"] - target_pc1) ** 2 + (df["PC2"] - target_pc2) ** 2 ) # 排除目标自身、按距离升序排序、取前3条、保留指定字段 result = df[df["ID"] != target_id] \ .sort_values(by="Distance", ascending=True) \ .head(3)[["ID", "PC1", "PC2", "Distance"]] # 输出结果,保留3位小数 print(result.round(3))
示例输出
以上代码运行后的输出如下:
ID PC1 PC2 Distance 4 34 0.367 0.533 0.120 0 12 0.355 0.362 0.158 1 24 0.577 0.425 0.326
内容的提问来源于stack exchange,提问作者Saa17
相关产品推荐
相关产品推荐

