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

Geopandas中按ID与通车年份合并相交LineString的问题

问题:合并满足条件且连通的道路线段

需求说明

  • 仅合并同时满足以下所有条件的Linestring:
    1. 拥有相同的id
    2. 拥有相同的通车年份opening
    3. 线段彼此连通/相交
  • 数据为道路数据库,使用GeoPandas进行处理

数据示例

id    opening    geometry
0   30    2020       LINESTRING (45.01679 -12.12937, 45.01681 -12...
1   101   1999       LINESTRING (37.02849 -10.65968, 37.02849 -10...
2   30    2019       LINESTRING (47.10667 -15.49339, 47.10665 -15...
3   101   1999       LINESTRING (41.64170 -12.45764, 41.64180 -12...
4   135   2020       LINESTRING (45.31902 -9.76800, 45.31907 -9.7...

第一次尝试代码及报错

代码

import geopandas as gpd
import numpy as np
import shapely

gdf_sof = gpd.read_file('your_path/your_file')

# 合并连通线段
gdf = gpd.GeoDataFrame()
for id in gdf_sof.id.unique():
  print(id)
  unique_id = gdf_sof.loc[gdf_sof.id == id]
  print(unique_id.shape)
  gdf_sof_id = gpd.GeoDataFrame()
  for dt in unique_id.opening.unique():
    print(dt)
    unique_oppening = unique_id.loc[unique_id.opening == dt]
    dissolved = gpd.geoseries.GeoSeries([geom for geom in unique_oppening.unary_union.geoms])
    gdf_sof_id = pd.concat([gdf_sof_id, dissolved], ignore_index=True, axis=0)
  gdf.concat(gdf_sof_id, ignore_index=True, axis=0, inplace=True)

gdf.shape

报错信息

---------------------------------------------------------------------------
AttributeError: 'LineString' object has no attribute 'geoms'

第二次尝试代码及问题

代码

import geopandas as gpd
import numpy as np
import pandas as pd
import shapely
from shapely.ops import linemerge

gdf_sof = gpd.read_file('your_path/your_file')

# 合并连通线段
gdf = gpd.GeoDataFrame()
for id in gdf_sof.id.unique():
  unique_id = gdf_sof.loc[gdf_sof.id == id]
  gdf_sof_id = gpd.GeoDataFrame()
  for dt in unique_id.opening.unique():
    unique_opening = unique_id.loc[unique_id.opening == dt]
    shp = shapely.get_parts(unique_opening.geometry)
    dissolved = linemerge(shp)
    gdf_dissolved = gpd.GeoDataFrame({'id': [id],
                                      'opening': [dt],
                                      'geometry':dissolved},
                                      geometry = 'geometry', 
                                      crs = gdf_sof.crs)
    gdf_sof_id = pd.concat([gdf_sof_id, gdf_dissolved], ignore_index=True, axis=0)
  gdf = pd.concat([gdf, gdf_sof_id], ignore_index=True, axis=0)

gdf.shape

问题

初始gdf_sof的形状为(7366, 3),最终gdf的形状为(973, 3),但错误合并了不相邻的线段:原本彼此不连通的多条道路线段(如图中高亮显示的部分),在处理后的属性表中被合并成了同一行记录,需要将这类不连通的线段分开保留。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:17:22