[GIS] geopandas: can’t save geojson

geojsongeopandas

My task is to upload geojson, add data from corresponding csv, drop some columns, then save it back to geojson.

However, after I did everything, added csv data (gj.join(df) ), etc,
I can't save it to geojson getting this Keyerror:

KeyError Traceback (most recent call last)
in ()
----> 1 x = newGj.to_json()
2 x

/usr/local/lib/python2.7/site-packages/geopandas/geodataframe.pyc in to_json(self, na, *kwargs)
249 return json.dumps(
250 {'type': 'FeatureCollection',
--> 251 'features': [feature(i, row) for i, row in self.iterrows()]},
252 *kwargs )
253

/usr/local/lib/python2.7/site-packages/geopandas/geodataframe.pyc in feature(i, row)
245 'properties':
246 dict((k, v) for k, v in iteritems(row) if k != self._geometry_column_name),
--> 247 'geometry': mapping(row[self._geometry_column_name]) }
248 
249 return json.dumps(

KeyError: None

Best Answer

what commands are you actually using?

EDIT lead with misleading/false "no way to 'write to geojson' " comment originally

Looking at the documentation I don't see a way to "write to geojson" other than geoDF.to_file() for which you'll get a shapefile or need to specify an OGR driver.

I like the below option using geoDF.to_json() better because it simply returns a GeoJSON formatted string.

Try something like this:

with open('test.geojson', 'w') as f:
    f.write(geoDF.to_json())

WARNING: it looks like GeoPandas.to_json() does not specify the CRS so reading back in the data GeoPandas.read_file() will assume your data are in WGS (EPSG=4326). I don't see how to specify the crs in the kwargs so for me easier to simply reproject the data (geoDF.to_crs(epsg=4326, inplace=True)) before writing to file.

Alternatively the below also works for me BUT

  • it gives me "WARNING:Fiona:CPLE_NotSupported in dataset .geojson does not support layer creation option ENCODING" when I read back in, and
  • not all geometries written using the to_file() method are equal to gemetries written with the f.write() method. I assume this has something to do with how GeoPandas handles the underlying driver but I haven't looked into it further

nyc_blocks.to_file('geoDF.geojson', driver="GeoJSON")

Related Question