MongoDB城市多边形数据转GeoDataFrame:几何列识别异常解决
解决MongoDB地理数据转GeoDataFrame时几何列不识别的问题
从你的代码和输出来看,直接将MongoDB返回的GeoJSON格式的geometry字典赋值给DataFrame列,GeoPandas无法自动识别为几何数据类型——GeoPandas需要的是shapely几何对象而非原始字典结构。以下是修正方案:
步骤1:导入必要依赖
确保你已安装geopandas和shapely,导入对应的模块:
import pandas as pd import geopandas as gpd from shapely.geometry import shape
步骤2:修正数据转换逻辑
修改原有代码,将MongoDB返回的GeoJSON geometry字典转换为shapely几何对象,再创建GeoDataFrame:
query = { 'properties.PROVINCIA': 'Ciudad' } consult = collection.find(query) df_result = pd.DataFrame(consult) # 解析properties字段到DataFrame df = pd.DataFrame.from_records(df_result['properties'].tolist()) # 将GeoJSON字典转换为shapely几何对象 df['geometry'] = df_result['geometry'].apply(lambda x: shape(x) if x is not None else None) # 创建GeoDataFrame,指定几何列 gdf = gpd.GeoDataFrame(df, geometry='geometry') # 验证结果 gdf.head()
关键说明
shape(x)函数会将GeoJSON格式的字典(比如包含type和coordinates的结构)转换为shapely的Polygon或MultiPolygon对象,这是GeoPandas能识别的几何类型。- 加入
if x is not None else None是为了处理可能存在的空几何数据,避免报错。 - 最终必须用
gpd.GeoDataFrame()来创建对象,而非普通的pd.DataFrame,这样才能启用GeoPandas的空间分析功能。
内容的提问来源于stack exchange,提问作者Vanessa
相关产品推荐
相关产品推荐

