Today I Learned

Create GeoPandas DataFrame From PostGIS

You can seamlessly read geometries directly from the PostGIS database into a GeoPandas dataframe. This greatly simplifies the process of accessing spatial datasets for analysis or visualization.

To accomplish this, the method from_postgis is used. This method precisely mandates three parameters:

  1. sql: This houses the SQL query which instructs which data set is to be fetched.
  2. con: This parameter stands for the connection to the PostGIS database.
  3. geom_col: This refers to the column name that houses the Geometry data.

The snippet below illustrates how these parameters are used:

import geopandas as gpd
import psycopg2

# Establishing a connection to the PostGIS database
con = psycopg2.connect(
    database="your database",
    user="user",
    password="password",
    host="your host"
)

# Specifying the SQL query to select data
sql = "SELECT x, y, z, geom FROM your_table"

# Instructing GeoPandas to read the data from PostGIS into a DataFrame
df = gpd.GeoDataFrame.from_postgis(sql, con, geom_col='geom')

With this, the geometric data from PostGIS is readily available in a GeoPandas DataFrame for your manipulations and analyses.