Search code examples
pythongeojsonshapefilegeopandasshapely

Shapely doesn't recognize the geometry type of geoJson


I'm a beginner with shapely and i'm trying to read shapefile, save it as geoJson and then use shape() in order to see the geometry type. according to the doc, shape():

shapely.geometry.shape(context) Returns a new, independent geometry with coordinates copied from the context.

Saving the shapefile as geoJson seems to work but for some reason when I try to use shape() on the geoJson I get error:

ValueError: Unknown geometry type: featurecollection

This is my script:

import geopandas
import numpy as np
from shapely.geometry import shape, Polygon, MultiPolygon, MultiLineString


#read shapefile:
myshpfile = geopandas.read_file('shape/myshape.shp')
myshpfile.to_file('myshape.geojson', driver='GeoJSON')


#read as GeoJson and use shape()
INPUT_FILE = 'shape/myshape.geojson'

geo_json = geopandas.read_file(INPUT_FILE)

#try to use shape()
geom = shape(geo_json)

>>>ValueError: Unknown geometry type: featurecollection

I have also tried to specify the geometry with slicing but seems like impossible.

#try to use shape()
geom = shape(geo_json.iloc[:,9])

>>>TypeError: '(slice(None, None, None), 9)' is an invalid key

Right now I can't pass this level, but my end goal is to be able to get the geometry type when print geom.geom_type (now I get the error before).

Edit:when I check the type of the saved GeoJson I get "geopandas.geodataframe.GeoDataFrame"


Solution

  • Your geo_json object is geopandas.GeoDataFrame which has a column of shapely geometries. There's no need to call shape. If you want to check geom_type, there's an easy way to do that directly.

    import geopandas
    import numpy as np
    from shapely.geometry import shape, Polygon, MultiPolygon, MultiLineString
    
    
    #read shapefile:
    myshpfile = geopandas.read_file('shape/myshape.shp')
    myshpfile.to_file('myshape.geojson', driver='GeoJSON')
    
    
    #read as GeoJson and use shape()
    INPUT_FILE = 'shape/myshape.geojson'
    
    geo_json = geopandas.read_file(INPUT_FILE)
    
    geo_json.geom_type
    

    That will give you geom_type for each geometry in the dataframe. Maybe check geopandas documentation to get more familiar with the concept.