You need to enable JavaScript to run this app. 如何使用GeoPandas将含两组经纬度的DataFrame转换为多段线
优惠活动
大模型
产品
解决方案
定价
更多

如何使用GeoPandas将含两组经纬度的DataFrame转换为多段线

解决方案

实现思路

每行数据对应一条由两个经纬度点组成的线段,逐行构造shapely.geometry.LineString对象即可生成线段类GeoDataFrame,后续可直接调用envelope属性生成外接多边形。

完整代码示例

import pandas as pd
import geopandas as gpd
from shapely.geometry import LineString
import matplotlib.pyplot as plt

# 假设你已有存储经纬度的原始df
# 1. 逐行构造LineString几何列
df['geometry'] = df.apply(
    lambda row: LineString([
        (row['long1'], row['lat1']), 
        (row['long2'], row['lat2'])
    ]), 
    axis=1
)

# 2. 转换为GeoDataFrame,指定WGS84坐标系(经纬度默认坐标系)
gdf_lines = gpd.GeoDataFrame(df, crs="EPSG:4326")

# 3. 生成外接多边形
# 方案1:每行线段对应独立的外接矩形
gdf_line_envelopes = gpd.GeoDataFrame(
    df.drop('geometry', axis=1),
    geometry=gdf_lines.envelope,
    crs=gdf_lines.crs
)

# 方案2:所有线段合并为一条多段线后生成全局外接矩形
full_multiline = gdf_lines.geometry.unary_union
global_envelope = full_multiline.envelope

# 可视化验证
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
ax = world[world.continent == 'North America'].plot(color='white', edgecolor='black')
gdf_lines.plot(ax=ax, color='green', linewidth=2)
gdf_line_envelopes.plot(ax=ax, color='red', alpha=0.3)
plt.show()

关键说明

  • 构造LineString时坐标传入顺序为(经度, 纬度),和points_from_xy的参数顺序保持一致
  • 如果需要生成多段线(MultiLineString)而非多个独立线段,直接调用gdf_lines.geometry.unary_union即可得到合并后的多段线对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 01:15:01