Search code examples
dataframegeometrygeojsongeopandas

convert geojson_geometry in json string to geodataframe


I have a string called "pois" obtained (from an API) like this:

[{'id': '1',
  'name': 'Blah1',
  'geometry_geojson': {'type': 'Point', 'coordinates': [-8.579082, 41.144294]}},
{'id': '2',
  'name': 'Blah2',
  'geometry_geojson': {'type': 'Point', 'coordinates': [-8.638596, 41.158304]}}]

And I need to convert it to a goedataframe to make some geospatial analysis. Any ideas on how can I achieve that?

My most succesful attempt has been to convert this string to a pandas dataframe by doing:

df = pd.json_normalize(pois)

But I obtain two columns "geometry_geojson.type" and "geometry_geojson.coordinates" (and also the columns "id" and "name"). Any ideas on how to convert these "geometry_geojson" element to a geodataframe's valid geometry?


Solution

  • Assuming pois is a Python string, you can use :

    from ast import literal_eval
    from shapely.geometry import shape
    ​
    tmp = pd.DataFrame(literal_eval(pois))
    ​
    gdf = gpd.GeoDataFrame(tmp, geometry= [shape(d) for d in tmp.pop("geometry_geojson")])
    

    Output :

    print(type(gdf))
    <class 'geopandas.geodataframe.GeoDataFrame'>
    
    print(gdf)
    
      id   name                   geometry
    0  1  Blah1  POINT (-8.57908 41.14429)
    1  2  Blah2  POINT (-8.63860 41.15830)
    

    enter image description here