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

使用GeoPandas计算Shapefile中多边形间的最近距离

计算美国各州多边形间的最小距离(GeoPandas实现)

步骤1:投影转换

原始Shapefile采用的GCS_North_American_1983是地理坐标系(经纬度),无法直接计算真实物理距离,必须先转换为适合美国区域的投影坐标系。推荐使用EPSG:5070(美国本土等面积投影,单位为米):

import geopandas as gpd
from itertools import combinations

# 加载Shapefile数据
shape_gdf = gpd.read_file('states.shp')

# 转换为投影坐标系
shape_gdf_proj = shape_gdf.to_crs(epsg=5070)

步骤2:生成州对组合

用itertools.combinations生成不重复的州对(避免重复计算CA-TX和TX-CA这类对称组合):

# 假设州缩写列名为'abbr',若实际列名是'STUSPS'或其他,请自行替换
state_pairs = combinations(shape_gdf_proj[['abbr', 'geometry']].itertuples(index=False), 2)

步骤3:计算每对州的最小距离

遍历州对,调用shapely的distance()方法计算多边形间的最小距离,再转换为千米或英里:

distance_results = []
for state1, state2 in state_pairs:
    # 计算距离(单位:米)
    distance_m = state1.geometry.distance(state2.geometry)
    # 转换为千米
    distance_km = distance_m / 1000
    # 转换为英里(可选)
    distance_mi = distance_m / 1609.34
    
    distance_results.append({
        'state1': state1.abbr,
        'state2': state2.abbr,
        'distance_km': round(distance_km, 2),
        'distance_mi': round(distance_mi, 2)
    })

# 转换为GeoDataFrame方便查看和导出
distance_gdf = gpd.GeoDataFrame(distance_results)
print(distance_gdf.head())

关键说明

  • 接壤的州会直接返回0作为距离(因为多边形边界相交,最小距离为0)。
  • 如果需要保留所有有序对(如同时保留CA-TX和TX-CA),可改用itertools.product,但计算量会翻倍。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 08:12:15