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

相关推荐
@PHARAOH22 分钟前
WHAT - GitLens vs Fork
前端
yqcoder36 分钟前
前端性能优化:如何减少重绘与重排?
前端·性能优化
洋子1 小时前
Yank Note 系列 13 - 让 AI Agent 进入笔记工作流
前端·人工智能
wenzhangli73 小时前
Ooder A2UI 核心架构深度解析:WEB 拦截层的设计与实现
前端·架构
前端百草阁4 小时前
【前端性能优化全链路指南】从开发编写到构建运行的多维度实践
前端·性能优化
女生也可以敲代码4 小时前
AI时代下的50道前端开发面试题:从基础到大模型应用
前端·面试
ZhengEnCi4 小时前
M5-markconv自定义CSS样式指南 📝
前端·css·python
IT_陈寒5 小时前
SpringBoot自动配置的坑差点让我加班到天亮
前端·人工智能·后端
xingpanvip5 小时前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua
@PHARAOH5 小时前
WHAT - GitLens supercharged 插件
前端