TransWikia.com

Geopandas and Zonal Statistic error

Geographic Information Systems Asked by Lorenzo Bottaccioli on April 2, 2021

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")
zonal_stats(geodf,"raster.tif")

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 "", line 1, in
zonal_stats(geodf,"raster.tif",stats=’mean’)
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
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
    Out[42]: 
         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?

One Answer

For anyone else that stumbles upon this you can do:

To get just one stat:

gdf['mean'] = pd.DataFrame(
    zonal_stats(
        vectors=gdf['geometry'], 
        raster='raster.tif', 
        stats='mean'
    )
)['mean']

To get all computed stats:

gdf = gdf.join(
    pd.DataFrame(
        zonal_stats(
            vectors=gdf['geometry'], 
            raster='raster.tif', 
            stats=['max','min']
        )
    ),
    how='left'
)

Answered by jwilson8767 on April 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP