地理数据处理库Geopandas如何连接PostGIS?

17

我最近开始在Python中使用Geopandas进行一些空间工作,并对其感到非常满意 - 我目前正在尝试读取PostGIS特征,但不太明白如何参数化数据库连接,并且文档中似乎也不是很清楚:

GeoDataFrame.from_postgis(sql, con, geom_col='geom', crs=None, index_col=None, 
    coerce_float=True, params=None)

这可能是一个非常简单的问题,我只是想知道在'con'中需要放什么 - 我假设是包含数据库连接信息的字符串?但是以什么格式?设置'sql'似乎很简单。任何帮助都将不胜感激 - 谢谢!


你可以查看pandas的read_sql文档,这是geopandas使用的:http://pandas.pydata.org/pandas-docs/stable/io.html#sql-queries - joris
谢谢 - 这正是我在寻找的! - mweber
2个回答

42

例子:

import geopandas as gpd

import psycopg2  # (if it is postgres/postgis)

con = psycopg2.connect(database="your database", user="user", password="password",
    host="your host")

sql = "select geom, x,y,z from your_table"

df = gpd.GeoDataFrame.from_postgis(sql, con, geom_col='geom' )

4
psycopg2 是针对 PostgreSQL 数据库的,而 sqlalchemy.create_engine() 则是通用的,可以处理大多数数据库管理系统的连接。 - Hugh_Kelley

0

看起来上面的例子不再适用,因为GeoPandas不接受con = psycopg2.connect(...),而是返回以下错误:

UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy.
  df = pd.read_sql(

现在似乎只有使用sqlalchemy.create_engine()这个方法了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接