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

如何计算pandas DataFrame列向量间的成对欧氏距离

Pandas 计算列两两欧氏距离方阵方案

核心逻辑

scipy的pdist方法默认计算输入矩阵行与行之间的距离,要计算DataFrame列与列的距离,只需将DataFrame转置后传入即可。

依赖导入

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

计算代码

# 可选:先处理缺失值,避免计算错误
df = df.dropna()

# 计算列两两欧氏距离
distance_array = pdist(df.T, metric="euclidean")
# 转为要求格式的方阵
distance_matrix = pd.DataFrame(
    squareform(distance_array),
    index=df.columns,
    columns=df.columns
)

结果验证

用你提供的样例数据运行后,输出的distance_matrix格式如下(数值为实际计算结果):

x_1x_2x_3
x_10.00000012952.0819367898.373630
x_212952.0819360.00000012394.723758
x_37898.37363012394.7237580.000000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:36:04