I'm trying to use Geopandas and zonal statistic from rasterstats together.

I run this code

import geopandas as gpd
from rasterstats import zonal_stats

geodf = gpd.read_file("SHP/shape.shp")

but I get this error:

ParseException: Unknown type: 'FID'
ParseException: Unexpected EOF parsing WKB
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2820, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-43-3d15c4dddd4f>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/rasterstats/main.py", line 21, in zonal_stats
return list(gen_zonal_stats(*args, **kwargs))
File "/usr/local/lib/python2.7/dist-packages/rasterstats/main.py", line 128, in gen_zonal_stats
for i, feat in enumerate(features_iter):
File "/usr/local/lib/python2.7/dist-packages/rasterstats/io.py", line 107, in <genexpr>
features_iter = (parse_feature(x) for x in obj)
File "/usr/local/lib/python2.7/dist-packages/rasterstats/io.py", line 70, in parse_feature
raise ValueError("Can't parse %s as a geojson Feature object" % obj)
ValueError: Can't parse FID as a geojson Feature object

The data frame looks like this:

In[43]: geodf
     FID                                      geometry

0     0  POLYGON ((7.662965420348624 45.05600185397847,...
1     1  POLYGON ((7.665210146514162 45.05607590098681,...
2     2  POLYGON ((7.663353281768154 45.05601113630467,...
3     3  POLYGON ((7.660229137844505 45.0570570693801, ...
4     4  POLYGON ((7.660047499767138 45.0572381357898, ...

Any suggestion how to solve this problem?

| improve this question | | | | |

For anyone else that stumbles upon this you can do gdf['mean'] = pd.DataFrame(zonal_stats(vectors=gdf['geometry'], raster='raster.tif', stats='mean'))['mean']

To get just one stat, or gdf = gdf.join(pd.DataFrame(zonal_stats(vectors=gdf['geometry'], raster='raster.tif', stats=['max','min'])), how='left') to get several.

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.