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

DataFrame转为Geopandas LineString后绘图提示数据非数值怎么解决

问题原因
  1. 执行分组聚合后得到的geo_df为普通Pandas Series类型,并非GeoDataFrame,缺少geopandas绘图依赖的geometry字段声明。绘图时geopandas无法将LineString识别为合法几何对象,会尝试将其解析为普通数值,最终触发非数值报错。
  2. 若存在仅包含1个点的分组,生成LineString时会产生无效几何对象,也会触发同类报错,若你确认转换阶段无警告则可排除该情况。
解决方法

标准转换流程

将聚合后的Series显式转换为GeoDataFrame,同时继承原有数据的坐标系即可:

# 分组生成LineString后转GeoDataFrame
line_gdf = gdf.groupby('station')['geometry'].apply(lambda x: LineString(x.tolist()))\
              .reset_index(name='geometry')
# 声明为GeoDataFrame,指定geometry列和坐标系
line_gdf = gpd.GeoDataFrame(line_gdf, geometry='geometry', crs=gdf.crs)

转换完成后直接调用line_gdf.plot()即可正常绘图。

保留属性补充方案

如果你需要保留原数据中除geometry外的其他数值属性,可在分组时同步做聚合处理:

line_gdf = gdf.groupby('station').agg(
    # 替换为你实际需要保留的数值列和聚合规则
    attr_avg=('你的数值列名', 'mean'),
    geometry=('geometry', lambda x: LineString(x.tolist()))
).reset_index()
line_gdf = gpd.GeoDataFrame(line_gdf, geometry='geometry', crs=gdf.crs)

单一点分组过滤方案

如果存在点数不足2的分组,提前过滤避免生成无效LineString:

line_gdf = gdf.groupby('station').filter(lambda x: len(x) >= 2)\
              .groupby('station')['geometry'].apply(lambda x: LineString(x.tolist()))\
              .reset_index(name='geometry')
line_gdf = gpd.GeoDataFrame(line_gdf, geometry='geometry', crs=gdf.crs)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:24:01