1

I have a geodataframe of several thousand rows, mixed geometry (Point, LineString, Polygon). I would like to write this out to a geopackage with different layers per geometry type. Here's what I've got so far (in jupyter nb):

import geopandas as gpd
%matplotlib inline

geojson_file = "C:/Temp/data.geojson"

gdf = gpd.read_file(geojson_file)

gdf.head() # yields good results
gdf.plot() # draws all the various geometries where they should be

gpkg = "C:/Temp/converted.gpkg"
gdf.to_file(gpkg, driver="GPKG")

Then when I load the layers...

import fiona
for ln in fiona.listlayers(gpkg):
    with fiona.open(gpkg, layer=ln) as dataset:
        print(ln, len(dataset))

it only gives me

converted 10000

Where am I going wrong?

EDIT: I'm on Windows 10, Python 3.8 (anaconda), and GeoPandas 0.8.1

2

Each layer of GeoPackage can contain a single geometry type not mixed. You have to save different geom types to separate layers.

import geopandas as gpd
%matplotlib inline

geojson_file = "C:/Temp/data.geojson"

gdf = gpd.read_file(geojson_file)

gdf.head() # yields good results
gdf.plot() # draws all the various geometries where they should be

gpkg = "C:/Temp/converted.gpkg"

for geomtype in gdf.geom_type.unique():
   gdf[gdf.geom_type == geomtype].to_file(gpkg, driver="GPKG", layer=geomtype)
| improve this answer | |
  • 1
    Gorgeous! I knew layers could only contain one geometric type, but I wasn't sure if geopandas (fiona) would break them out automatically into their primitives. I'll set myself a task next week to pull the documentation and submit a generic version of your answer for inclusion. – auslander Oct 2 at 14:19
  • I was maybe wrong. GPKG can have multiple geoms and for points and polygons IO with geopandas works, so there may be something else happening. – martinfleis Oct 2 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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