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

5

我在一个GeoPandas数据框中有一列字符串,格式如下:'{type=Point, coordinates=[37.55, 55.71]}' 或者 '{type=MultiPoint, coordinates=[[37.6, 55.4]]}'。它也可以是多边形或其他任何几何形状。然后还有一些以嵌套列表的形式表示的点。我该如何将其转换为普通的GeoPandas几何对象呢?

3个回答

5
使用shapely.geometry.shape将GeoJSON字符串转换为Shapely几何体。
from shapely.geometry import shape

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

它返回 AttributeError: 'str' object has no attribute 'get',调试器指向行 geom_type = ob.get("type").lower() - James Flash
我明白了。这不是合适的JSON格式,所以出现了这个问题。你可以尝试将字符串转换为类似JSON的格式,并在shape之前使用json.loads,或者手动重新生成几何图形。也许有人会知道更好的方法。 - martinfleis
是的,在我的情况下我做到了,但我可能没有使用最好的方法。请查看我的答案。 - James Flash

0

从这个源代码:在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)

0
我按照以下方式实现了它。感谢@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('=',':'))))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接