5

I have a column in a GeoPandas dataframe with strings like this one '{type=Point, coordinates=[37.55, 55.71]}' or this '{type=MultiPoint, coordinates=[[37.6, 55.4]]}'. It can be a polygon or any other geometry as well. Then there are a few points in the form of nested list. How can I transform it to the ordinary GeoPandas geometry objects?

Georgy
  • 12,464
  • 7
  • 65
  • 73
James Flash
  • 528
  • 7
  • 15

3 Answers3

5

Use shapely.geometry.shape to convert geojson strings to shapely geometry.

from shapely.geometry import shape

df['geometry'] = df.apply(lambda: row: shape(row['jsoncolumn']), axis=1)
martinfleis
  • 7,124
  • 2
  • 22
  • 30
  • It returns `AttributeError: 'str' object has no attribute 'get'` and the debugger points at the line `geom_type = ob.get("type").lower()` – James Flash Feb 04 '20 at 10:36
  • I see. It is not proper JSON, that is why. You can try to convert your string into JSON-like one and use `json.loads` before `shape` or somehow regenerate geometries manually. Maybe someone will know better way. – martinfleis Feb 04 '20 at 12:58
  • Yeah, I did it in my case but I probably didn't use the best method. See my answer – James Flash Feb 04 '20 at 13:26
0

I implemented it as follows. Thanks to @martinfleis

# Add necessary shapes and keys
coordinates = 'coordinates'
type = 'type'
Point = 'Point'
MultiPoint = 'MultiPoint'
Polygon = 'Polygon'
MultiPolygon = 'MultiPolygon'
center='center'

df['geometry'] = df.geoData.apply(lambda x: shape(eval(x.replace('=',':'))))
James Flash
  • 528
  • 7
  • 15
0

From this source : on github

I built the following function :

import geopandas as gpd
import geojson
import json

def geojsonification(x):
    
    geom = x['geom']

    if type(geom) == dict:
        s = json.dumps(geom)
        s2 = geojson.loads(s)
        res = shape(s2)
        return res
    else:
        return np.nan

Which you can use as this :

gdf.geometry = gdf.apply(geojsonification, axis=1)
Basile
  • 575
  • 1
  • 6
  • 13