Import shapefiles using GeoPandas and PsycoPG2.

GeoPandas and PsycoPG2

GeoPandas is great python library to process your vector data. It has direct support for postgis database where you can directly read/write from/to postgis database. GeoPandas internally uses SqlAlchemy API to manage database specific operations like reading from PostGIS, writing to PostGIS etc. SqlAlchemy can be used for almost all the databases out there like PostgreSQL, MySQL, Oracle Database, SQL Server.

GeoPandas provides read_postgis and to_postgis methods to read/write from/to PostGIS database. These methods take SqlAlchemy connection object to read/write from/to database. These methods provides very simple, elegant method to read and write from/to PostGIS database.

Psycopg2 is used only with PostgreSQL database. GeoPandas read_postgis method also works with Psycopg2 connection object. But to_postgis doesn’t work with Psycopg2 connection object.

GeoPandas to_postgis don’t support PsycoPG2. We have created multiple methods to support this functionality and are self explanatory. See code snippet below. We will talk mainly about to_postgis_using_psycopg2 method defined at line number 59 at below code snippet.
We will focus mainly at line number 74 where we are converting GeoDataframe geometries to WKB(Web Known Binary text) hexadecimal string using to_wkb method of PYGEOS module.
WKB hexadecimal string is a type of encoding that PostGIS use to store geometrical data.
By converting geometries to WKB hexadecimal string, we are making easy for postgis to insert the database from GeoDataFrame. Once we have converted the geometries to WKB hexadecimal string, we are converting the GeoDatafame to tuple and then finally inserting it to Database. See line number 81.

I hope this tutorial will create a good foundation for you. If you want tutorials on another GIS topic or you have any queries, please send an email at

1 thought on “Import shapefiles using GeoPandas and PsycoPG2.”

  1. Pingback: Building a Custom Geocoding Service with Autocomplete using Python, PostGIS, and OpenLayers for Address Lookup - Spatial Dev Guru

Leave a ReplyCancel reply