question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Error writing out geopackage with Polygons and MultiPolygons

See original GitHub issue

I’m running into an error when trying to write the following test GeoDataFrame into a .gpkg file:

import geopandas
db = geopandas.read_file('test.geojson')
db.to_file('test.gpkg', driver='GPKG')

Which returns:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-f5a4384ca577> in <module>()
      1 db = geopandas.read_file('test.geojson')
----> 2 db.to_file('test.gpkg', driver='GPKG')

~/anaconda/envs/gds/lib/python3.6/site-packages/geopandas/geodataframe.py in to_file(self, filename, driver, schema, **kwargs)
    411         """
    412         from geopandas.io.file import to_file
--> 413         to_file(self, filename, driver, schema, **kwargs)
    414
    415     def to_crs(self, crs=None, epsg=None, inplace=False):

~/anaconda/envs/gds/lib/python3.6/site-packages/geopandas/io/file.py in to_file(df, filename, driver, schema, **kwargs)
    109         with fiona.open(filename, 'w', driver=driver, crs=df.crs,
    110                         schema=schema, **kwargs) as colxn:
--> 111             colxn.writerecords(df.iterfeatures())
    112
    113

~/anaconda/envs/gds/lib/python3.6/site-packages/fiona/collection.py in writerecords(self, records)
    333         if self.mode not in ('a', 'w'):
    334             raise IOError("collection not open for writing")
--> 335         self.session.writerecs(records, self)
    336         self._len = self.session.get_length()
    337         self._bounds = self.session.get_extent()

fiona/ogrext.pyx in fiona.ogrext.WritingSession.writerecs()

ValueError: Record's geometry type does not match collection schema's geometry type: 'MultiPolygon' != 'Polygon'

This is on ‘0.4.0’ and the test file is available here. If I try the same operation in QGIS, I have no issue. Any suggestion why?

Issue Analytics

  • State:open
  • Created 5 years ago
  • Comments:15 (13 by maintainers)

github_iconTop GitHub Comments

11reactions
ljwolfcommented, Oct 31, 2018

Sorry, should’ve posted this when I initially commented. My code reads:

from shapely import geometry
upcast_dispatch = {geometry.Point: geometry.MultiPoint, 
                   geometry.LineString: geometry.MultiLineString, 
                   geometry.Polygon: geometry.MultiPolygon}

def maybe_cast_to_multigeometry(geom):
    caster = upcast_dispatch.get(type(geom), lambda x: x[0])
    return caster([geom])

I would do this any time we’re writing in a schema we know supports only one geometry type & we see a df.geometry.unique() with both instances of multi and single types.

I can probably manage a PR with this by end of week.

0reactions
attilabibokcommented, Jun 14, 2022

This thread seems a bit old and long-running, but I faced a similar issue recently with: Fiona 1.8.21 geopandas 0.10.2

It only failed on polygons though. Only a single geometry type was in the geoDataframe.

The problem was resolved after casting the Polygons to MultiPolygons.

Exception has occurred: TypeError  Cannot interpret '<geopandas.array.GeometryDtype object at 0x7f6652e35e80>' as a data type
  File "/env_nwm_network/lib/python3.8/site-packages/geopandas/io/file.py", line 414, in convert_type
    out_type = type(np.zeros(1, in_type).item()).__name__
Read more comments on GitHub >

github_iconTop Results From Across the Web

Polygons and MultiPolygons should follow the right-hand rule
I used it for past 3 years without any problem with my old GeoJSON file. Now geojsonlint enforce the right hand rule, how...
Read more >
write multicurve/multisurface into GPKG error - FME Community
There are GML/FGDB dataset with "round conner polygon" or multilines geometry which is mixed "curve and lines". It can't be written into GPKG...
Read more >
Handling Invalid Geometries (QGIS3) - QGIS Tutorials and Tips
We now know that this particular state polygon had invalid geometry but we don't know what was the cause. We can easily find...
Read more >
st_write refuses to overwrite layers in geopackage in R
... `ESRI Shapefile' Writing 100 features with 14 fields and geometry type Multi Polygon. ## Error here, as it already exists. st_write(nc, ...
Read more >
1 The Fiona User Manual — Fiona 2.0dev documentation
The GeoJSON format turns out to be a good model for a Python API. ... 'Polygon' in its schema may yield either 'Polygon'...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found