GeoPandas+DataFrame实现shapefile文件导入PostGIS数据库

首先,确保你的环境已经安装了必要的库。你需要 geopandas, sqlalchemy, psycopg2 (或 psycopg2-binary), 和 geoalchemy2。可以通过以下命令安装:

pip install geopandas sqlalchemy psycopg2-binary geoalchemy2

上代码

python 复制代码
import geopandas as gpd
from sqlalchemy import create_engine
 
# 读取Shapefile
gdf = gpd.read_file('./files/par/par.shp')
 
 
# 如果需要,转换坐标系统至合适的SRID(例如WGS 84的EPSG:4326)
gdf = gdf.to_crs(epsg=4326)
# 设置编码
# gdf.columns = [col.encode('GBK') for col in gdf.columns]
# 检查当前几何列
print("当前活跃几何列:", gdf._geometry_column_name)
print("所有列:", gdf.columns.tolist())
gdf
 
try:
    db_config = {
    "host": "X",       # 例如 "localhost"
    "port": "5432",       # 例如 "5432"
    "database": "postgres",
    "user": "postgres",
    "password": "XX"
    }
 
# 2. 创建SQLAlchemy引擎
# 连接字符串格式:postgresql://用户名:密码@主机:端口/数据库名
    engine = create_engine(f'postgresql://{db_config["user"]}:{db_config["password"]}@{db_config["host"]}:{db_config["port"]}/{db_config["database"]}')
# # 导入数据到PostGIS
    gdf.to_postgis(
        name='传感器数据',  # 数据库中目标表名
        con=engine,
        if_exists='replace',     # 表存在时的操作:'replace'替换,'append'追加,'fail'失败
        index=True              # 不建议将DataFrame索引作为列导入
    )
    print("数据已成功导入PostGIS!")
except Exception as e:
    print(e)

查看结果 可以看到,字段的类型没有完全都转为string

相关推荐
Highcharts.js14 小时前
缺失数据可视化图表开发实战|Highcharts创建人员出生统计面积图表示例
开发语言·前端·javascript·信息可视化·highcharts·图表开发
LaughingZhu20 小时前
Product Hunt 每日热榜 | 2026-05-21
前端·人工智能·经验分享·chatgpt·html
怕浪猫21 小时前
Electron 开发实战(一):从零入门核心基础与环境搭建
前端·electron·ai编程
小鹏linux21 小时前
Ubuntu 22.04 部署开源免费具有精美现代web页面的Casdoor账号管理系统
linux·前端·ubuntu·开源·堡垒机
前端若水1 天前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
Bigger1 天前
mini-cc:一个轻量级 AI 编程助手的诞生
前端·ai编程·claude
涵涵(互关)1 天前
Naive-ui树型选择器只显示根节点
前端·ui·vue
BY组态1 天前
Ricon组态系统最佳实践:从零开始构建物联网监控平台
前端·物联网·iot·web组态·组态
BY组态1 天前
Ricon组态系统vs传统组态软件:为什么选择新一代Web组态平台
前端·物联网·iot·web组态·组态
SoaringHeart1 天前
Flutter进阶:OverlayEntry 插入图层管理器 NOverlayZIndexManager
前端·flutter