栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将GeoDataFrame写入SQL数据库

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将GeoDataFrame写入SQL数据库

因此,我只是为PostGIS数据库实现了这一点,可以在这里粘贴我的方法。对于MySQL,您必须修改代码。

第一步是在地理编码列转换为WKB十六进制字符串,因为我使用SQLAlchemy的,基于发动机pyscopg,并且这两个包的不理解地理类型本身。下一步是照常将数据写入SQL
DB(请注意,所有几何列都应转换为包含WKB十六进制字符串的文本列),最后通过执行查询将列的类型更改为几何。请参考以下伪代码:

# importsimport sqlalchemy as salimport geopandas as gpd# Function to generate WKB hexdef wkb_hexer(line):    return line.wkb_hex# Convert `'geom'` column in GeoDataframe `gdf` to hex    # Note that following this step, the GeoDataframe is just a regular Dataframe    # because it does not have a geometry column anymore. Also note that    # it is assumed the `'geom'` column is correctly datatyped.gdf['geom'] = gdf['geom'].apply(wkb_hexer)# Create SQL connection engineengine = sal.create_engine('postgresql://username:password@host:socket/database')# Connect to database using a context managerwith engine.connect() as conn, conn.begin():    # Note use of regular Pandas `to_sql()` method.    gdf.to_sql(table_name, con=conn, schema=schema_name,    if_exists='append', index=False)    # Convert the `'geom'` column back to Geometry datatype, from text    sql = """ALTER TABLE schema_name.table_name    ALTER COLUMN geom TYPE Geometry(LINESTRING, <SRID>)      USING ST_SetSRID(geom::Geometry, <SRID>)"""    conn.execute(sql)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/394082.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号