[GIS] Pandas to GeoPandas : Polygon Geometry, WKTReadingError

geopandaspandaspostgispythonshapely

I read a PostGIS table with pandas : df = pd.read_sql_table(con=engine, table_name)

The column geom contains the geometry of my entity, it is a polygon geometry.
I want to convert the DataFrame to a GeoDataFrame with :

from shapely import wkt
df.loc[:, 'geom'] = df.loc[:, 'geom'].apply(wkt.loads)

Here is the answer:

ParseException: Unknown type: '01060000206A080000010000000103000000010000001700000026FDBD944CB828410C5A48CD852B5A41F629C7744AB82841BA15C252842B5A412C82FF9548B82841A73E9011842B5A417B9FAAFA22B82841B1355BE08C2B5A411A321E0DEFB728416631B13B952B5A41CA349AE401B828419F58A7909F2B5A411C06F37746B82841F4A5B77AA12B5A41172994DD58B82841BFD71000A72B5A414AD40B1694B8284127DA5543B32B5A417E1B62DCB8B8284177D84486BB2B5A41D540F321DDB82841C7F0D87FBB2B5A413C122F0F07B928419A7B4826B62B5A413A3B191C39B92841516B9A59B42B5A415918225F3EB92841028239FDA62B5A41D2FBC68FBFB9284168D0D0E9AD2B5A415F402F8CD3B92841761728E0AB2B5A418D7DC98EFBB92841096CCE8CA72B5A4103D2FE27FDB92841234BE6CCA32B5A41A67C08029EB92841B5183C119C2B5A41710514BA57B92841DCB8C5AD9C2B5A4125E659B9F8B82841959A3DF2942B5A416D74CE5FF0B828418D2958F3902B5A4126FDBD944CB828410C5A48CD852B5A41'
WKTReadingError: Could not create geometry because of errors while reading input.

I also tried :

df.loc[:, 'geom'] = df.loc[:, 'geom'].map(shapely.wkt.loads)

And I got the same anwser as above.
Any ideas to proceed the conversion ?

Best Answer

The docs have just a brief mention of it, but GeoPandas has a read_postgis method. Maybe give that a try:

import geopandas as gpd
from sqlalchemy import create_engine

sql = f'select * from {tablname};'
eng = create_engine(
    (f'postgresql://{db_user}:{db_pass}@'
     f'{db_url}:{db_port}/{db_name}')
)

gdf = gpd.read_postgis(sql, eng, crs='epsg:4326')
Related Question