Import Shapefile to PostgreSQL/PostGIS database using GeoPandas/Python

The usage of Python in GeoSpatial field has exponentially grown. Almost every GIS desktop software provide python integration. QGIS, famous open source GIS software, has python interface. Python has many open source GIS libraries for example GDAL, Fiona, GeoPandas, RasterIO, Shapely, Xarray Spatial etc. These libraries can process both raster as well as vector data.

In this tutorial, we will create shapefiles import tool using GeoPandas which will import shapefiles to PostgreSQL/PostGIS database. PostgreSQL is famous free open source relational database and PostGIS is extension to PostgreSQL which allows storage of raster and vector data in PostgreSQL database.

GeoPandas is an open source project to make working with geospatial data in python easier. It provides many functions to perform spatial operations.

In this post, we will utilize GeoPandas to import shapefiles to PostGIS database. We will use SQLAlchemy to create database connection which GeoPandas will use to import shapefiles to database.

Let’s understand following code block. At line number 1 and 2, we are importing GeoPandas and SQLAlchemy.

From line number 4 to 8, we defining some database connection information like user name, password etc.

At line number 10 and 11, we are creating a postgresql database connection.

At line number 14, we are reading a shapefile using GeoPandas.

At line number 16, we are using to_postgis method of GeoDataFrame gdf object to import shapefile to database. It receives schema name, table name and sql connection object as arguments.

Congratulations, you have successfully imported shapefile to database. This to_postgis function does work under the hood.

GeoPandas pairs really well with PostGIS, similar to to_postgis, it has from_postgis method which can be used to read data from postgis to GeoPandas. GeoPandas comes really handy when you want process gis data using Python

6 thoughts on “Import Shapefile to PostgreSQL/PostGIS database using GeoPandas/Python”

  1. aborrell – Live in Guadalajara, Mexico Works in GIS projects with open software

    Interesting artcle, but the code view is incomplete, only through line 16.

  2. Pingback: Import Shapefile to PostgreSQL/PostGIS database using GeoPandas/Python –

  3. Pingback: Import rasters file to PostGIS database using raster2pgsql - Spatial Dev Guru

  4. Pingback: Merging multiple shapefiles into one shapefile using python and GeoPandas - Spatial Dev Guru

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

Leave a ReplyCancel reply