3

I want to read my data on postgis using geopandas but it won't read. It works on Linestring data, but not on Polygon. When I open the postgis data using QGIS and it works fine, the polygon reads good. Here's my code:

import psycopg2
import geopandas as gpd

con = psycopg2.connect(user = "postgres",
                      password = "admin",
                      host = "127.0.0.1",
                      port = "5432",
                      database = "spatial")
cursor = con.cursor()
sql = "SELECT * FROM public.polygonData"
df = gpd.GeoDataFrame.from_postgis(sql, con)

if(con):
            cursor.close()
            con.close()
df

and this is the error. I wonder why it won't read the polygon as enclosed? How do I fix this?

IllegalArgumentException: Points of LinearRing do not form a closed linestring
---------------------------------------------------------------------------
WKBReadingError                           Traceback (most recent call last)
<ipython-input-10-b3bfe339a21d> in <module>
      6 cursor = con.cursor()
      7 sql = "SELECT * FROM public.polygonData"
----> 8 df = gpd.GeoDataFrame.from_postgis(sql, con)
      9 
     10 if(con):

~\anaconda3\lib\site-packages\geopandas\geodataframe.py in from_postgis(cls, sql, con, geom_col, crs, index_col, coerce_float, parse_dates, params)
    362             coerce_float=coerce_float,
    363             parse_dates=parse_dates,
--> 364             params=params,
    365         )
    366 

~\anaconda3\lib\site-packages\geopandas\io\sql.py in read_postgis(sql, con, geom_col, crs, index_col, coerce_float, parse_dates, params)
     89             load_geom = load_geom_text
     90 
---> 91         df[geom_col] = geoms = geoms.apply(load_geom)
     92         if crs is None:
     93             srid = shapely.geos.lgeos.GEOSGetSRID(geoms.iat[0]._geom)

~\anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
   3846             else:
   3847                 values = self.astype(object).values
-> 3848                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   3849 
   3850         if len(mapped) and isinstance(mapped[0], Series):

pandas\_libs\lib.pyx in pandas._libs.lib.map_infer()

~\anaconda3\lib\site-packages\geopandas\io\sql.py in load_geom_text(x)
     77         def load_geom_text(x):
     78             """Load from binary encoded as text."""
---> 79             return shapely.wkb.loads(str(x), hex=True)
     80 
     81         if sys.version_info.major < 3:

~\anaconda3\lib\site-packages\shapely\wkb.py in loads(data, hex)
     13     reader = WKBReader(lgeos)
     14     if hex:
---> 15         return reader.read_hex(data)
     16     else:
     17         return reader.read(data)

~\anaconda3\lib\site-packages\shapely\geos.py in read_hex(self, data)
    439         if not geom:
    440             raise WKBReadingError(
--> 441                 "Could not create geometry because of errors "
    442                 "while reading input.")
    443         # avoid circular import dependency

WKBReadingError: Could not create geometry because of errors while reading input.

my geopandas version is 0.7.0.
my osgeo version is 3.0.4.
My Psycopg2 version is '2.8.6 (dt dec pq3 ext lo64)'.

1 Answer 1

1

The polygons are likely invalid. Each ring must have the same 1st and last point. Some readers will silently correct issues like this while other will just throw an error.

You can detect them and learn why they are invalid

SELECT st_isvalidreason(geom)
FROM public.polygonData
WHERE st_isvalid(geom) = false;

And then you can attempt to fix them

UPDATE public.polygonData
SET geom = st_makevalid(geom)
WHERE st_isvalid(geom) = false;
1
  • Thanks. Unfortunately, when I run the SELECT script It does not return any rows; all the rows are valid geometry. I tried changing the WHERE clause to true and it returned all of the rows. conclusion, the geometry is valid, but to geopandas it is not valid!
    – sutan
    Commented Nov 9, 2020 at 19:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.