将一列类似 GeoJSON 的字符串转换为 GeoPandas 中的几何对象

Convert a column of GeoJSON-like strings to geometry objects in GeoPandas

我在 GeoPandas 数据框中有一个列,其中包含像这个 '{type=Point, coordinates=[37.55, 55.71]}' 或这个 '{type=MultiPoint, coordinates=[[37.6, 55.4]]}' 这样的字符串。它也可以是多边形或任何其他几何体。然后是嵌套列表形式的几点。如何将其转换为普通的 GeoPandas 几何对象?

使用 shapely.geometry.shape 将 geojson 字符串转换为匀称的几何图形。

from shapely.geometry import shape

df['geometry'] = df.apply(lambda: row: shape(row['jsoncolumn']), axis=1)

我是这样实现的。感谢@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('=',':'))))

来源:on github

我构建了以下函数:

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

你可以这样使用:

gdf.geometry = gdf.apply(geojsonification, axis=1)