将 GeoPandas 数据框中的几何图形检索为 json [编辑:使用 .to_json()]

Retrieving geometry in GeoPandas dataframe as json [Edit: use .to_json()]

将 geojson 文件加载到 GeoPandas 后,我得到了名为 "geometry" 的预期列/特征,其中包含多边形和多边形。

如何将此对象作为 json 或 Python 字典再次取出?

在当前形式下,它是一个 geopandas.geoseries.GeoSeries 对象。

例如,我需要这样的东西:

geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -73.76336816099996, 40.726165522000031 ], [ -73.762895342999968, 40.726101379000056 ], [ -73.761940118999973, 40.725972874000036 ], [ -73.76074889399996, 40.725792699000067 ] ] ] ] }

在文档中没有看到任何内容:

http://geopandas.org/data_structures.html#overview-of-attributes-and-methods

如果你有一个GeoSeries对象(或者GeoDataFrame,下面是一样的),比如

>>> import geopandas
>>> from shapely.geometry import Point
>>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2)])
>>> s
0    POINT (1 1)
1    POINT (2 2)
dtype: object

然后你可以使用 __geo_interface__:

将其转换为类似 GeoJSON 的字典
>>> s.__geo_interface__
{'bbox': (1.0, 1.0, 2.0, 2.0),
 'features': [{'bbox': (1.0, 1.0, 1.0, 1.0),
   'geometry': {'coordinates': (1.0, 1.0), 'type': 'Point'},
   'id': '0',
   'properties': {},
   'type': 'Feature'},
  {'bbox': (2.0, 2.0, 2.0, 2.0),
   'geometry': {'coordinates': (2.0, 2.0), 'type': 'Point'},
   'id': '1',
   'properties': {},
   'type': 'Feature'}],
 'type': 'FeatureCollection'}

或使用 to_json 方法到实际的 GeoJSON(json 版本的上述字典):

>>> s.to_json()
'{"type": "FeatureCollection", "bbox": [1.0, 1.0, 2.0, 2.0], "features": [{"id": "0", "type": "Feature", "geometry": {"coordinates": [1.0, 1.0], "type": "Point"}, "bbox": [1.0, 1.0, 1.0, 1.0], "properties": {}}, {"id": "1", "type": "Feature", "geometry": {"coordinates": [2.0, 2.0], "type": "Point"}, "bbox": [2.0, 2.0, 2.0, 2.0], "properties": {}}]}'

在此示例中,它 returns 一个字符串,但如果您传递文件路径,它会将其写入文件。