如何提取Pandas DataFrame中的GeoJSON并转为GeoDataFrame及文件?
解决方案:提取GeoJSON并转换为GeoDataFrame
前置依赖
确保已安装所需库:
pip install pandas geopandas shapely
1. 解析GeoJSON字符串列
首先将DataFrame中存储的GeoJSON字符串解析为Python字典:
import pandas as pd import json import geopandas as gpd from shapely.geometry import shape # 你的测试数据 data = {'Geojson': ['{"geometry": {"coordinates": [[[24.950899, 60.169158], [24.953492, 60.169158],[24.953510, 60.170104],[24.950958, 60.169990]]],"type": "Polygon"},"id": 1,"properties": {"GlobalID": "84756blabla","NAME": "Helsinki Senate Square","OBJECTID": 1,"OBS_CREATEDATE": 1641916981000,"OBS_UPDATEDATE": null, "Area_m2": 6861.47},"type": "Feature"}'],'Name': ["Helsinki Senate Square"], 'Type': ["Polygon"]} df = pd.DataFrame(data) # 解析每个GeoJSON字符串 df['geojson_parsed'] = df['Geojson'].apply(json.loads)
2. 保存为完整GeoJSON文件
将所有解析后的Feature对象组合成标准的FeatureCollection格式,再写入文件:
# 构建FeatureCollection结构 feature_collection = { "type": "FeatureCollection", "features": df['geojson_parsed'].tolist() } # 写入GeoJSON文件 with open('output.geojson', 'w', encoding='utf-8') as f: json.dump(feature_collection, f, ensure_ascii=False, indent=2)
3. 转换为GeoPandas GeoDataFrame
提取几何对象和属性字段,转换为GIS场景常用的GeoDataFrame:
# 将GeoJSON几何转换为Shapely对象 df['geometry'] = df['geojson_parsed'].apply(lambda x: shape(x['geometry'])) # 提取并展开properties属性为单独列(可选,简化后续数据分析) properties_df = pd.json_normalize(df['geojson_parsed'].apply(lambda x: x['properties'])) # 合并数据列,生成GeoDataFrame gdf = gpd.GeoDataFrame( pd.concat([df.drop(['Geojson', 'geojson_parsed'], axis=1), properties_df], axis=1), geometry='geometry', crs='EPSG:4326' # 示例坐标为WGS84经纬度,对应EPSG:4326 )
4. 多几何类型支持说明
shape()函数可自动识别并转换所有标准GeoJSON几何类型(Point、Polygon、MultiLineString、MultiPolygon等),无需额外修改代码,只要原始GeoJSON格式符合规范即可。
验证结果
# 查看GeoDataFrame基本信息 print(gdf.head()) # 查看包含的几何类型 print(gdf.geometry.type.unique())
内容的提问来源于stack exchange,提问作者William_Boot
相关产品推荐
相关产品推荐

