You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas如何高效生成所有行两两欧氏距离的16x16 DataFrame

高效实现两两坐标欧氏距离计算的方案

首先提取坐标列的numpy数组备用:

coords = df[['cx', 'cy']].values

方法1:scipy pdist实现(最推荐)

专门用于点对距离计算的API,代码最简洁,自动输出符合要求的方阵:

from scipy.spatial.distance import pdist, squareform
import pandas as pd

# 计算所有点对的欧氏距离,输出压缩形式的一维数组
dist_compress = pdist(coords, metric='euclidean')
# 转换为16×16的距离方阵,对角线自动为0
dist_matrix = squareform(dist_compress)
# 转换为DataFrame,行名列名默认继承原df的索引,可按需调整
df_distances = pd.DataFrame(dist_matrix, index=df.index, columns=df.index)

方法2:纯numpy广播实现(无第三方依赖需求时用)

仅用numpy的广播机制实现,不需要额外安装其他库:

import numpy as np
import pandas as pd

# 维度扩展后广播计算坐标差
coord_diff = coords[:, np.newaxis, :] - coords[np.newaxis, :, :]
# 沿最后一个维度计算二范数,即欧氏距离
dist_matrix = np.linalg.norm(coord_diff, axis=2)
df_distances = pd.DataFrame(dist_matrix, index=df.index, columns=df.index)

方法3:sklearn pairwise_distances实现(已有sklearn环境时用)

如果项目已经引入sklearn,可直接调用其封装好的距离计算接口:

from sklearn.metrics.pairwise import euclidean_distances
import pandas as pd

dist_matrix = euclidean_distances(coords)
df_distances = pd.DataFrame(dist_matrix, index=df.index, columns=df.index)

以上三种方案均为向量化的底层C实现,既避免了手写双重循环的繁琐,运行效率也远高于Python原生循环,且自动保证对角线为0的要求。

内容的提问来源于stack exchange,提问作者JDS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 06:36:05