zadrozny
zadrozny

Reputation: 1731

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

Having loaded a geojson file into GeoPandas, I get the expected column / feature called "geometry", containing polygons and multipolygons.

How do I get this object out again as a json or Python dict?

In it's current form, it is a geopandas.geoseries.GeoSeries object.

For example, I need something like:

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

Not seeing anything on this in the doc:

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

Upvotes: 3

Views: 4488

Answers (1)

joris
joris

Reputation: 139162

If you have a GeoSeries object (or a GeoDataFrame, the below works the same), such as

>>> 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

then you can convert this to a GeoJSON-like dict with __geo_interface__:

>>> 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'}

or to actual GeoJSON (json version of the dict above) with the to_json method:

>>> 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": {}}]}'

In this example it returns a string, but if you pass a file path, it will write that to the file.

Upvotes: 5

Related Questions