[GIS] Import PostGis tables into a GeoDataframe unexpected : ‘AttributeError: ‘NoneType’ object has no attribute ‘encode”

geopandaspostgispython

When I try to import two of my tables from postgis to geopandas I have an error. I guess the problem is due to my geometry columun, but I don't know why.

engine = create_engine('postgresql+psycopg2://xxx:xx@host/db')
sql = 'Select * FROM table'
GeoDF= gpd.GeoDataFrame.from_postgis(sql, engine)

It works great for most of my tables but two tables can't be imported, I have the message : 'AttributeError: 'NoneType' object has no attribute 'encode''

AttributeError                            Traceback (most recent call last)
<ipython-input-16-80c4e8c0de28> in <module>()
      1 sql = 'Select * FROM table'
----> 2 GeoDF= gpd.GeoDataFrame.from_postgis(sql, engine)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\geopandas\geodataframe.py in from_postgis(cls, sql, con, geom_col, crs, index_col, coerce_float, params)
    235         """
    236         return geopandas.io.sql.read_postgis(sql, con, geom_col, crs, index_col,
--> 237                      coerce_float, params)
    238 
    239     def to_json(self, na='null', show_bbox=False, **kwargs):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\geopandas\io\sql.py in read_postgis(sql, con, geom_col, crs, index_col, coerce_float, params)
     40     wkb_geoms = df[geom_col]
     41 
---> 42     s = wkb_geoms.apply(lambda x: shapely.wkb.loads(binascii.unhexlify(x.encode())))
     43 
     44     df[geom_col] = GeoSeries(s)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
   3190             else:
   3191                 values = self.astype(object).values
-> 3192                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   3193 
   3194         if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()

~\AppData\Local\Continuum\anaconda3\lib\site-packages\geopandas\io\sql.py in <lambda>(x)
     40     wkb_geoms = df[geom_col]
     41 
---> 42     s = wkb_geoms.apply(lambda x: shapely.wkb.loads(binascii.unhexlify(x.encode())))
     43 
     44     df[geom_col] = GeoSeries(s)

AttributeError: 'NoneType' object has no attribute 'encode'

Best Answer

Found the answer! Some rows add a null geometry, if you add a where to select only the rows where the gemetry is not null it works!