[GIS] GeoPandas to PostGIS database

geopandaspostgispostgresqlpython

New to using GeoPandas instead of Pandas. I am trying to export a GeoPandas dataframe to a PostgreSQL database (with PostGIS extension).

The import is from the same database as I try to export to using:

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

The CRS seems to be imported as well as srid=25832. When I print gdf.crs it yields as expected:

{'init': 'epsg:25832'}

A sample of the geodataframe looks like this, where the last column geom (the geometry) seems to be the problem child:

row_num     model  ...  mean_res                            geom  
0          1  644862.0  ...  37.40605  POINT (573187.125 6131561.456)  
1          2  644862.0  ...  36.36506  POINT (573189.374 6131560.369)  
2          3  644862.0  ...  35.42172  POINT (573191.623 6131559.282)  
3          4  644862.0  ...  34.90574  POINT (573193.873 6131558.194)  
4          5  644862.0  ...  34.36104  POINT (573196.122 6131557.107)  
..       ...       ...  ...       ...                             ...  
116      117  644862.0  ...  41.61498  POINT (573448.099 6131435.305)  
117      118  644862.0  ...  41.26093  POINT (573450.350 6131434.217)  
118      119  644862.0  ...  41.39089  POINT (573452.600 6131433.129)  
119      120  644862.0  ...  41.49015  POINT (573454.851 6131432.041)  
120      121  644862.0  ...  41.56080  POINT (573457.101 6131430.954)  

My problem is when I try to export the dataframe using:

df.to_sql(tablename, con=engine, schema=schemaname, if_exists='replace', index=False)

The engine is from the SQLAlchemy lib using psycopg2, which is working for a "normal" Pandas dataframe (i.e. without geometry)

I get the error:

"Table could not be edited: databasename.schemaname.tablename  
'GeometryDtype' object has no attribute 'base'"

Best Answer

GeoPandas will support postGIS from the next release. At this moment, you can try using this branch https://github.com/geopandas/geopandas/pull/1248 which brings that support or just get the code from it.

Since geopandas 0.8.0 you will be able to do df.to_postgis(tablename, con=engine, schema=schemaname, if_exists='replace', index=False).

Related Question