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

如何将自定义距离函数应用到DataFrame每行以计算欧氏距离?

代码修正方案

首先明确计算逻辑:从你给出的示例结果可以看出,需求是计算当前行坐标与上一行坐标的欧氏距离,首行无前置参考行因此结果为空。

原有代码问题

  • 自定义的measure_distance函数硬编码了两个固定坐标点,没有使用传入的x、y参数,也没有返回计算结果
  • apply调用逻辑错误,包含不存在的add函数、参数传递错误、列索引方式错误

修正后可直接运行的逐行实现代码

import numpy as np
import pandas as pd

# 定义距离计算函数,传入前后两个点的坐标数组返回欧氏距离
def measure_distance(p_prev, p_curr):
    return np.linalg.norm(p_curr - p_prev)

# 生成每行的坐标数组临时列
df['point'] = df.apply(lambda row: np.array([row['Coordinate x'], row['Coordinate y']]), axis=1)

# 逐行计算与上一行的距离
df['Desired Output/Distance between coords'] = df.apply(
    lambda row: measure_distance(df['point'].shift(1)[row.name], row['point']) if row.name > 0 else np.nan,
    axis=1
)

# 删除临时列
df.drop('point', axis=1, inplace=True)

高性能向量化实现(推荐,适合大数据量场景)

无需逐行调用apply,直接用numpy向量化运算,性能提升显著:

# 提取坐标转为numpy数组
coords = df[['Coordinate x', 'Coordinate y']].values
# 计算相邻行坐标差值
diff = coords[1:] - coords[:-1]
# 计算距离,首行补空值
distances = np.concatenate([[np.nan], np.linalg.norm(diff, axis=1)])
# 赋值到结果列
df['Desired Output/Distance between coords'] = distances

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:51:03