python-rasterstats icon indicating copy to clipboard operation
python-rasterstats copied to clipboard

DOC: How to link the results back to fields in the shapefile ?

Open sylvaticus opened this issue 3 years ago • 1 comments

Let's say by shapefile has a field "RegionName", and I want to compute some zonal statistics from a raster, e.g. a count.

I can do stats = zonal_stats("myAdminBorders.shp", "myData.tif"), but then my stats is a vector. How can I then link this vector back to the shapefile RegionName (and possibly export all as CSV or similar) ?

sylvaticus avatar Apr 22 '21 08:04 sylvaticus

You can use geopandas to read the shapefile initially and pass into zonal stats. The stats output can be converted directly to a pandas dataframe, appended with the RegionName field, and saved to a csv.

import geopandas as gpd
import rasterstats
import pandas as pd

shp = gpd.read_file('myAdminBorders.shp')
stats = rasterstats.zonal_stats(shp, "myData.tif")
stats = pd.DataFrame(stats)
stats['RegionName'] = shp['RegionName']
stats.to_csv('region_stats.csv')

sdtaylor avatar Jun 07 '21 13:06 sdtaylor

The stats are listed in the same order as the input features.

If you want to retain the attributes, you can pass geojson_out=True so that the output is a complete copy of the original feature plus additional columns. https://pythonhosted.org/rasterstats/manual.html?highlight=geojson#geojson-output - you can take this result and write it to shapefile or whatever you want using other tools like fiona

perrygeo avatar Jan 15 '23 02:01 perrygeo