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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
from sqlalchemy import create_engine import geopandas as gpd user = "postgres" password = "admin" host = "localhost" port = 5432 database = "postgis_in_action" conn = f"postgresql://{user}:{password}@{host}:{port}/{database}" engine = create_engine(conn) #Read shapefile using GeoPandas gdf = gpd.read_file("boundary_shp/boundary.shp") #Import shapefile to databse gdf.to_postgis(name="boundary", con=engine, schema="public") print("success") |
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
Interesting artcle, but the code view is incomplete, only through line 16.
Pingback: Import Shapefile to PostgreSQL/PostGIS database using GeoPandas/Python – GeoNe.ws
Hi aborrell, open in Google Chrome. Mozilla may have that issue
Pingback: Import rasters file to PostGIS database using raster2pgsql - Spatial Dev Guru
Pingback: Merging multiple shapefiles into one shapefile using python and GeoPandas - Spatial Dev Guru
Pingback: Building a Custom Geocoding Service with Autocomplete using Python, PostGIS, and OpenLayers for Address Lookup - Spatial Dev Guru