求助:调用sjoin()进行空间连接为何返回空GeoDataFrame?
空间连接返回空GeoDataFrame的问题排查与解决
问题概述
尝试将关联姓名的点GeoDataFrame与法国地籍多边形GeoDataFrame做内连接(op="within"),预期匹配坐标在多边形内的Melynn和Gaspard,但结果为空。两者CRS均标注为EPSG:2154。
原始代码
点数据构建
data = {'Noms (z)': ['Melynn','Paul','David','Gaspard'], 'lat': [49.46138,49.4404591,49.4404591, 49.46138], 'long': [1.07948,1.0939658,1.0939658, 1.07948]} df = pd.DataFrame(data) # 注意:此处坐标顺序存在错误 pts = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df['lat'], df['long'], crs="EPSG:2154"))
多边形数据加载与筛选
shapes = gpd.read_file("../Data sets/cadastre-76-sections-shp/sections.shp") subshapes = shapes[shapes['commune']=='76451']
空间连接代码
gpd.sjoin(pts, subshapes, how="inner", op="within")
核心问题与修复步骤
1. 坐标顺序错误(最可能原因)
gpd.points_from_xy的参数顺序为X轴(经度)在前,Y轴(纬度)在后,你将纬度(lat)放在了X参数位置、经度(long)放在Y参数位置,导致点的实际位置完全偏离目标区域。
修正后的点GeoDataFrame代码:
pts = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df['long'], df['lat'], crs="EPSG:2154"))
2. 验证多边形子集有效性
检查subshapes是否为空,避免筛选条件错误:
print(subshapes.shape) # 若输出(0, ...),说明commune值匹配错误
法国地籍数据中commune字段可能为数值类型,尝试用数值筛选:
subshapes = shapes[shapes['commune'] == 76451]
3. 可视化确认位置关系
用可视化直观验证点是否在多边形范围内:
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(10, 8)) subshapes.plot(ax=ax, color='lightblue', edgecolor='black') pts.plot(ax=ax, color='red', markersize=60) plt.title("点与多边形位置关系") plt.show()
4. 再次确认CRS一致性
即使标注一致,仍需验证CRS是否完全匹配:
print("点CRS:", pts.crs) print("多边形CRS:", subshapes.crs)
若不一致,统一CRS:
subshapes = subshapes.to_crs(pts.crs)
内容的提问来源于stack exchange,提问作者Gaspard_Boyer
相关产品推荐
相关产品推荐

