Skip to content
Advertisement

Export properties into .geojson file using geopandas

I have a script that creates a lot of Polygons using Shapely and then exports them as .geojson files. See toy example below

from shapely.geometry import Polygon
import geopandas

roi = Polygon([(0,0), (0,1), (1,0), (1,1)])
rois = [roi, roi]

geopandas.GeoSeries(rois).to_file("detection_data.geojson", driver='GeoJSON')

However, I also have a list of numbers, each number is associated with one ploygon. Is there a way to export this with the GeoJSON file inside properties?

For example, if I have a list:

detection_prob = [0.8, 0.9]

In the .geojson file I would like the properties section for the first polygon to read

“properties”:{“detection_prob”:0.8}

and for the second polygon

“properties”:{“detection_prob”:0.9}

etc etc etc… in the outputted GeoJSON file.

Advertisement

Answer

If you call to_file on a dataframe instead of a series, you can add extra attributes as columns:

import geopandas as gpd
import shapely.geometry as g

df = gpd.GeoDataFrame({
    'geometry': [g.Point(0, 0), g.Point(1,1)],
    'name': ['foo', 'bar']
})
df.to_file('out.json', driver='GeoJSON')
Advertisement