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

解决Shapely将DataFrame两点转为LineString的弃用警告问题

问题描述

我有如下DataFrame:

ID_from  ID_to  geometry_to                      geometry_from
0   DE111    DE111  POINT (4260741.157 2851183.129)  POINT (4260741.157 2851183.129)
1   DE111    DE112  POINT (4243568.080 2841580.049)  POINT (4260741.157 2851183.129)
2   DE111    DE113  POINT (4274165.690 2838336.792)  POINT (4260741.157 2851183.129)

尝试用以下代码将两个POINT转换为LineString:

df_line['Line'] = df_line.apply(lambda row: LineString([row['geometry_from'], row['geometry_to']]), axis=1)

运行后能得到预期结果,但会收到如下警告:

ShapelyDeprecationWarning: The array interface is deprecated and will no longer work in Shapely 2.0. Convert the '.coords' to a numpy array instead.
  arr = construct_1d_object_array_from_listlike(values)

请问应如何修改代码以避免该警告?

解决方案

这个警告源于Shapely 2.0不再支持直接将Point对象传入LineString构造器的旧实现,需要改用提取坐标的方式来创建LineString,以下是两种可行的修改方案:

方案一:修改apply中的lambda逻辑

直接提取Point对象的坐标传入LineString:

df_line['Line'] = df_line.apply(lambda row: LineString([row['geometry_from'].coords[0], row['geometry_to'].coords[0]]), axis=1)

方案二:使用向量化操作提升效率(推荐大数据量场景)

避免逐行apply,改用shapely.linestrings批量创建LineString:

from shapely import linestrings

# 提取两列Point的坐标列表
from_coords = df_line['geometry_from'].apply(lambda p: p.coords[0]).tolist()
to_coords = df_line['geometry_to'].apply(lambda p: p.coords[0]).tolist()

# 批量生成LineString并赋值
df_line['Line'] = linestrings([[from_p, to_p] for from_p, to_p in zip(from_coords, to_coords)])

核心原理

.coords[0]会返回Point对象的坐标元组(例如(4260741.157, 2851183.129)),将这些坐标元组传入LineString构造器,完全符合Shapely 2.0的API要求,因此可以消除该弃用警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:20:40