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

在DataFrame中筛选经纬度差值均≤0.01的地址对并执行比对算法

找出DataFrame中经纬度差值均≤0.01的地址对

你需要从给定的DataFrame里筛选出纬度差值≤0.01且经度差值≤0.01的地址对,当前代码只处理了纬度条件,还会输出重复配对(比如行0和行1的对,反过来又输出行1和行0),下面是改进的实现方式:

首先还原你的DataFrame数据:

import pandas as pd

data = {
    'Address': ['123 Main St New York', '896 Smith Ave New York', '40 E Main St, New York', '123 Main Street New York'],
    'State': ['New York', 'NY', 'Ny', 'New York'],
    'ZipCode': ['14787', '14787', '14787', '14787'],
    'Lat': [42.320889, 42.319874, 42.323447, 42.321889],
    'Long': [-79.573733, -79.571941, -79.574977, -79.573933]
}
df = pd.DataFrame(data)

现有代码的问题

  • 仅遍历Lat列数值,无法关联对应的Long值,没法同时判断经度条件
  • 会生成重复配对(比如(i,j)和(j,i)都会输出),造成冗余

方法一:通过索引遍历,避免重复配对

直接遍历行索引,只处理i < j的情况,确保每个配对仅被检查一次,同时获取对应行的经纬度进行判断:

# 遍历所有行索引对,i < j避免重复输出
for i in range(len(df)):
    for j in range(i + 1, len(df)):
        # 获取两行的经纬度
        lat1, lon1 = df.loc[i, 'Lat'], df.loc[i, 'Long']
        lat2, lon2 = df.loc[j, 'Lat'], df.loc[j, 'Long']
        
        # 判断经纬度差值是否均≤0.01
        if abs(lat1 - lat2) <= 0.01 and abs(lon1 - lon2) <= 0.01:
            addr1 = df.loc[i, 'Address']
            addr2 = df.loc[j, 'Address']
            print(f"符合条件的地址对:\n{addr1}\n{addr2}\n经纬度差值:纬度差={abs(lat1-lat2):.6f},经度差={abs(lon1-lon2):.6f}\n")

方法二:用itertools.combinations简化代码

用itertools.combinations生成所有不重复的行对,代码更简洁:

from itertools import combinations

# 生成所有不重复的行索引对
for idx1, idx2 in combinations(df.index, 2):
    lat_diff = abs(df.loc[idx1, 'Lat'] - df.loc[idx2, 'Lat'])
    lon_diff = abs(df.loc[idx1, 'Long'] - df.loc[idx2, 'Long'])
    
    if lat_diff <= 0.01 and lon_diff <= 0.01:
        print(f"地址对:\n{df.loc[idx1, 'Address']}\n{df.loc[idx2, 'Address']}")
        print(f"纬度差:{lat_diff:.6f},经度差:{lon_diff:.6f}\n")

运行结果

你的数据中所有地址对的经纬度差值都≤0.01,所以输出如下:

符合条件的地址对:
123 Main St New York
896 Smith Ave New York
经纬度差值:纬度差=0.001015,经度差=0.001792

符合条件的地址对:
123 Main St New York
40 E Main St, New York
经纬度差值:纬度差=0.002558,经度差=0.001244

符合条件的地址对:
123 Main St New York
123 Main Street New York
经纬度差值:纬度差=0.001000,经度差=0.000200

符合条件的地址对:
896 Smith Ave New York
40 E Main St, New York
经纬度差值:纬度差=0.003573,经度差=0.003036

符合条件的地址对:
896 Smith Ave New York
123 Main Street New York
经纬度差值:纬度差=0.002015,经度差=0.001992

符合条件的地址对:
40 E Main St, New York
123 Main Street New York
经纬度差值:纬度差=0.001558,经度差=0.001044

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 11:24:17