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

如何将含FeatureCollection列的Pandas DataFrame转换为GeoJSON

将含GeoJSON列的Pandas DataFrame转换为GeoJSON文件

方法一:使用GeoPandas(推荐)

GeoPandas专门处理地理空间数据,导出GeoJSON的流程更简洁高效:

  1. 导入所需库
import pandas as pd
import json
import geopandas as gpd
from shapely.geometry import shape
  1. 解析site_registration_gps_area列的JSON字符串
# 假设你的DataFrame变量名为df
df['parsed_geo'] = df['site_registration_gps_area'].apply(json.loads)
  1. 提取几何对象与属性信息
# 从FeatureCollection中提取Polygon几何
df['geometry'] = df['parsed_geo'].apply(lambda x: shape(x['features'][0]['geometry']))
# 提取原GeoJSON自带的属性
df['properties'] = df['parsed_geo'].apply(lambda x: x['features'][0]['properties'])
  1. 合并DataFrame其他列到属性中
# 将原DataFrame的非地理列全部加入properties字典
for col in df.columns:
    if col not in ['parsed_geo', 'geometry', 'properties']:
        df['properties'] = df.apply(lambda row: {**row['properties'], col: row[col]}, axis=1)
  1. 创建GeoDataFrame并导出
gdf = gpd.GeoDataFrame(df, geometry='geometry')
# 导出为GeoJSON文件
gdf.to_file('output.geojson', driver='GeoJSON')

方法二:纯Python(无需GeoPandas)

如果不想额外安装GeoPandas,可手动构建GeoJSON结构:

  1. 导入库并初始化Feature列表
import pandas as pd
import json

# 假设DataFrame为df
features = []
  1. 遍历每行构建Feature对象
for _, row in df.iterrows():
    # 解析单元格中的GeoJSON字符串
    geo_collection = json.loads(row['site_registration_gps_area'])
    # 获取FeatureCollection中的第一个Feature
    feature = geo_collection['features'][0]
    # 将DataFrame其他列添加到Feature的properties中
    for col in df.columns:
        if col != 'site_registration_gps_area':
            feature['properties'][col] = row[col]
    features.append(feature)
  1. 构建完整FeatureCollection并写入文件
geojson_result = {
    "type": "FeatureCollection",
    "features": features
}

# 写入文件,indent参数用于格式化输出,可选
with open('output.geojson', 'w', encoding='utf-8') as f:
    json.dump(geojson_result, f, indent=2)

注意事项

  • 你的DataFrame中已有geometry列(POINT类型),上述方法会将其替换为site_registration_gps_area中的Polygon几何;若需保留POINT,可将提取的Polygon重命名为其他列(如polygon_geometry),再调整后续步骤。
  • 处理10000行数据时,两种方法都能稳定运行,GeoPandas在大型数据集上的性能表现更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:55:16