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

如何将Pandas DataFrame转为GeoDataFrame?转换报错求助

问题:Excel转GeoDataFrame时触发TypeError错误

读取Excel文件后尝试转换为GeoDataFrame,执行代码如下:

import pandas as pd 
import geopandas as gpd
df = pd.read_excel('Centroids.xlsx')
df.head()

输出的DataFrame内容:

servicename                          servicecentroid
0   Mönchengladbach, Kreisfreie Stadt   POINT (4070115.425463234 3123463.773862813)
1   Mettmann, Kreis                     POINT (4109488.971501033 3131686.7549837814)
2   Düsseldorf, Kreisfreie Stadt        POINT (4098292.026333667 3129901.416880203)

执行转换代码时出现错误:

gdf = gpd.GeoDataFrame(df, geometry='servicecentroid')

报错信息:

TypeError: Input must be valid geometry objects: POINT (4070115.425463234 3123463.773862813)

问题原因与解决方法

问题根源

servicecentroid列中的内容是WKT格式的字符串文本,而非GeoPandas可识别的几何对象(shapely库的Point实例)。GeoPandas创建GeoDataFrame时,geometry参数要求传入已解析的几何对象,无法直接处理纯文本格式的坐标字符串。

解决步骤

使用GeoPandas的from_wkt方法,将WKT字符串转换为几何对象后再创建GeoDataFrame:

import pandas as pd 
import geopandas as gpd

# 读取Excel数据
df = pd.read_excel('Centroids.xlsx')

# 将WKT字符串列转换为几何对象列
df['geometry'] = gpd.GeoSeries.from_wkt(df['servicecentroid'])

# 创建GeoDataFrame
gdf = gpd.GeoDataFrame(df, geometry='geometry')

# 可选:删除原字符串列
gdf = gdf.drop('servicecentroid', axis=1)

执行上述代码后,就能成功生成包含有效几何对象的GeoDataFrame。


内容的提问来源于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.18 20:40:31