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

Pandas计算连续行经纬度距离时遇dtype错误求助

问题排查与修复:Haversine函数计算DataFrame连续行距离报错

报错原因

你代码里的np.radians([lat1, lon1, lat2, lon2])是把四个Pandas Series打包成列表传给np.radians,但NumPy的这个函数无法直接处理包含Series的列表——它需要的是可直接转换为数组的输入(比如单个Series或多维数组),而非Series组成的列表,因此抛出了“loop of ufunc does not support argument 0 of type Series...”的错误。

修复方案

直接对每个Series单独转弧度,或者将四个Series合并成二维数组后统一转换,两种方式都能解决问题:

方案1:逐个处理参数(直观易懂)

def haversine(lat1, lon1, lat2, lon2, to_radians=True, earth_radius=6371):
    if to_radians:
        lat1 = np.radians(lat1)
        lon1 = np.radians(lon1)
        lat2 = np.radians(lat2)
        lon2 = np.radians(lon2)

    a = np.sin((lat2-lat1)/2.0)**2 + \
        np.cos(lat1) * np.cos(lat2) * np.sin((lon2-lon1)/2.0)**2

    return earth_radius * 2 * np.arcsin(np.sqrt(a))

方案2:合并为数组后转换(更简洁)

def haversine(lat1, lon1, lat2, lon2, to_radians=True, earth_radius=6371):
    if to_radians:
        # 将四个Series合并为二维数组,转弧度后拆分回原参数
        coords = np.column_stack([lat1, lon1, lat2, lon2])
        lat1, lon1, lat2, lon2 = np.radians(coords).T

    a = np.sin((lat2-lat1)/2.0)**2 + \
        np.cos(lat1) * np.cos(lat2) * np.sin((lon2-lon1)/2.0)**2

    return earth_radius * 2 * np.arcsin(np.sqrt(a))

调用代码优化

原调用中df.loc[1:, 'lat']的长度比df.lat.shift()少一行,可直接用原Series让Pandas自动对齐索引,写法更简洁:

# 确保DataFrame已按需求排序
df['dist'] = haversine(df.lat.shift(), df.lng.shift(), df.lat, df.lng)

此时dist列第一行为NaN(对应shift后的空值),后续行即为连续行的经纬度距离,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:42:21