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

GeoPandas中英国部分礼仪郡点面空间匹配失败问题求助

英国礼仪郡Shapefile空间匹配失败问题(Cornwall/大伦敦/Rutland)

问题背景

我使用英国礼仪郡边界Shapefile(坐标系为British National Grid,EPSG:27700),需要将一个包含WGS84经纬度的位置DataFrame中的每个点匹配到所属礼仪郡。大部分郡的空间连接正常,但Cornwall、大伦敦(Greater London)和Rutland的点始终返回NaN,尽管可视化显示这些点明显位于对应郡的边界内。

代码

import geopandas as gpd
from shapely.geometry import Point

regions = gpd.read_file("Ceremonial_County_Boundaries.shp")

points = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df["lon"], df["lat"]))
points_bng = points.to_crs(regions.crs)

# 空间连接
joined = gpd.sjoin(points_bng, regions, how="left", predicate="within")

问题详情

空间连接可正确匹配约90%的位置,但Cornwall、大伦敦和Rutland的所有点均匹配失败(index_right = NaN)。检查这些区域的几何有效性:

county_poly = regions[regions["NAME"] == "Cornwall"]
print("Valid:", county_poly.geometry.is_valid.unique())

输出:

Valid: [False]

大伦敦和Rutland的几何有效性检查结果同样为False,其他所有郡的几何均有效且匹配正常。

已尝试操作

  • 可视化确认点位于多边形内部:绘图显示点明显在Cornwall/伦敦/Rutland边界内。
  • 确认坐标系正确:Shapefile为EPSG:27700,点已从EPSG:4326转换为EPSG:27700。

解决方案思路

问题根源是这三个区域的几何图形存在拓扑错误(无效),导致Shapely的within空间判断无法正常工作,修复无效几何即可解决:

方法1:使用buffer(0)快速修复

该方法能处理大部分常见的拓扑错误(如自相交、多边形方向问题):

# 修复所有区域的几何
regions['geometry'] = regions['geometry'].buffer(0)

方法2:使用make_valid()全面修复(需GDAL 3.1+)

对于更复杂的拓扑错误,推荐使用Shapely的make_valid方法:

from shapely.validation import make_valid

regions['geometry'] = regions['geometry'].apply(make_valid)

验证修复效果

修复后再次检查几何有效性:

target_counties = ["Cornwall", "Greater London", "Rutland"]
print(regions[regions["NAME"].isin(target_counties)].geometry.is_valid.unique())

预期输出为[True],之后重新运行空间连接即可正常匹配这些区域的点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 23:12:38