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

Python中遍历多列拆分坐标并计算所有组合距离的方法

问题描述

有如下格式的坐标数据:

Coordinates_location   Coordinates_degree             Coordinates_job
29.75, -95.36          29.75, -95.36                 29.75, 95.36; 29.75, -95.36
32.77, -96.79          30.72, -95.55                 32.7762719, -96.79
29.75, -95.36          30.44, -91.18; 33.18, -97.14  29.75, -95.36; 29.97, -90.07; 29.75, -95.36; 29.75, -95.36

其中Coordinates_degree和Coordinates_job列可能包含多个坐标,以分号分隔。需要遍历每一行,计算该行内所有可能的两两坐标组合的距离(比如第三行需覆盖所有坐标间的配对计算)。

最初尝试的代码无法实现预期效果,调用geodesic时报错,代码如下:

for a, b,c in all_coordinates.itertuples(index=False):
  for s, sp in zip(b.split(';'), c.split(';')):
      splitb.append(s)
      splitc.append(sp)
  for z, x, y in zip(a, splitb, splitc):
      total_distance.append(geodesic(z, x))
      total_distance.append(geodesic(x, y))
      total_distance.append(geodesic(z, y))
正确实现方法

核心思路:对每行数据,先收集该行所有的坐标(包含三列的所有单个坐标),生成所有不重复的两两组合后,再计算每对的距离。

步骤说明

  1. 坐标收集与格式转换:对每行的三个列分别处理,拆分多坐标、去除空格,将字符串格式的坐标转为(纬度, 经度)的数值元组(geodesic要求的输入格式)。
  2. 生成两两组合:用itertools.combinations生成所有无序两两配对,避免重复计算(距离是双向相等的)。
  3. 逐行独立处理:每行单独收集坐标,防止跨行列的坐标混合。

完整代码示例

from geopy.distance import geodesic
import itertools
import pandas as pd

# 示例DataFrame,替换为你的实际数据
all_coordinates = pd.DataFrame({
    'Coordinates_location': ['29.75, -95.36', '32.77, -96.79', '29.75, -95.36'],
    'Coordinates_degree': ['29.75, -95.36', '30.72, -95.55', '30.44, -91.18; 33.18, -97.14'],
    'Coordinates_job': ['29.75, 95.36; 29.75, -95.36', '32.7762719, -96.79', '29.75, -95.36; 29.97, -90.07; 29.75, -95.36; 29.75, -95.36']
})

total_distance = []

for _, row in all_coordinates.iterrows():
    row_coords = []
    
    # 处理Coordinates_location(单个坐标)
    loc_coord = row['Coordinates_location'].strip()
    lat, lon = map(float, loc_coord.split(','))
    row_coords.append((lat, lon))
    
    # 处理Coordinates_degree(多坐标拆分)
    for coord_str in row['Coordinates_degree'].split(';'):
        coord_str = coord_str.strip()
        if coord_str:
            lat, lon = map(float, coord_str.split(','))
            row_coords.append((lat, lon))
    
    # 处理Coordinates_job(多坐标拆分)
    for coord_str in row['Coordinates_job'].split(';'):
        coord_str = coord_str.strip()
        if coord_str:
            lat, lon = map(float, coord_str.split(','))
            row_coords.append((lat, lon))
    
    # 生成所有两两组合并计算距离
    for coord1, coord2 in itertools.combinations(row_coords, 2):
        dist = geodesic(coord1, coord2)
        total_distance.append(dist)
        # 可选:打印坐标对和距离用于验证
        # print(f"{coord1} - {coord2}: {dist}")

# 查看计算结果
print(total_distance)

关键细节

  • 加入空字符串检查:避免拆分后出现空坐标导致转换错误。
  • 用itertools.combinations高效生成组合:比如第三行共7个坐标,会生成21组有效配对,完全覆盖所有需要计算的组合。
  • 坐标格式严格转换:确保传入geodesic的是数值元组,避免类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 05:52:04