实现ListA经纬度点与ListB点的2500米范围校验并返回Y/N结果
英国邮政编码经纬度范围匹配需求
我有一批关联经纬度(lat/long)的英国邮政编码数据,需要完成以下操作:
- 将ListA中的每个经纬度点与ListB中的所有点进行比对
- 为ListA的每一行返回Y/N值,标识该点是否处于ListB中任意点的2500米范围内
以下是演示用的小规模数据集(实际数据集各包含数百条记录):
ListA
| Postcode | Lat | Long |
|---|---|---|
| PE36 6LQ | 52.97426 | 0.5526301 |
| NR23 1DR | 52.97246 | 0.8495693 |
ListB
| Postcode | Lat | Long |
|---|---|---|
| PE36 6LD | 52.9565 | 0.55366 |
| RM18 8PB | 52.97246 | 0.8495693 |
预期结果
| Postcode | Lat | Long | Within2500m |
|---|---|---|---|
| PE36 6LQ | 52.97426 | 0.5526301 | Y |
| NR23 1DR | 52.97246 | 0.8495693 | N |
解决方案
方法1:Python + Geopy计算球面距离
用geopy库的distance函数直接计算两点球面距离,判断是否在2500米范围内:
from geopy.distance import geodesic import pandas as pd # 构造示例数据(实际使用时替换为你的数据源) list_a = pd.DataFrame({ 'Postcode': ['PE36 6LQ', 'NR23 1DR'], 'Lat': [52.97426, 52.97246], 'Long': [0.5526301, 0.8495693] }) list_b = pd.DataFrame({ 'Postcode': ['PE36 6LD', 'RM18 8PB'], 'Lat': [52.9565, 52.97246], 'Long': [0.55366, 0.8495693] }) # 提取ListB的经纬度点集合 b_points = list(zip(list_b['Lat'], list_b['Long'])) # 定义判断函数 def check_range(row): a_point = (row['Lat'], row['Long']) for b_point in b_points: if geodesic(a_point, b_point).meters <= 2500: return 'Y' return 'N' # 生成结果列 list_a['Within2500m'] = list_a.apply(check_range, axis=1) print(list_a)
运行后输出结果与预期一致:
Postcode Lat Long Within2500m 0 PE36 6LQ 52.97426 0.5526301 Y 1 NR23 1DR 52.97246 0.8495693 N
方法2:SQL空间查询(数据库存储场景)
如果数据存在支持空间函数的数据库(如PostgreSQL+PostGIS),可直接用空间函数计算:
SELECT a.Postcode, a.Lat, a.Long, CASE WHEN EXISTS ( SELECT 1 FROM list_b b WHERE ST_Distance( ST_SetSRID(ST_MakePoint(a.Long, a.Lat), 4326), ST_SetSRID(ST_MakePoint(b.Long, b.Lat), 4326) ) <= 2500 ) THEN 'Y' ELSE 'N' END AS Within2500m FROM list_a a;
内容的提问来源于stack exchange,提问作者JeffWithpetersen
相关产品推荐
相关产品推荐

