I have a shapefile of polygons that I brought into Python in Jupyter Notebook via GeoPandas as a geodataframe. There are hundreds of polygons in this shapefile, and I want to create an individual raster for each polygon, where each raster has that rasterized polygon isolated, as if it were the only polygon, where each output raster has a unique number attached to it (e.g. "Output_raster_35" etc.). I want to specifically burn in values corresponding to each polygon within the "Values" column in this geodataframe.
I am trying to use the geocube
package for this task by running the following to rasterize the whole shapefile:
vector_fn = 'polygons.shp'
out_grid = make_geocube(
vector_data=vector_fn,
measurements=["Values"],
resolution=(-25, 25),
fill=-9999,
)
out_grid["Values"].rio.to_raster("my_rasterized_column.tif")
This code was suggested from this stackoverflow post: Rasterizing polygons in shapefile using GDAL
However, I need to iterate this process over each polygon (row), rather than rasterizing all polygons at once.
So far my idea is:
polygons = gpd.read_file('polygons.shp')
polygon_IDs = polygons.Polygon_ID.tolist()
for i in polygon_IDs:
x = polygons.loc[polygons.Polygon_ID == i]
vector_fn = x
out_grid = make_geocube(
vector_data=vector_fn,
measurements=["Values"],
resolution=(-25, 25),
fill=-9999,
)
out_grid["Values"].rio.to_raster("Output_Raster")
Though I am having trouble sorting out whether I have my logic and syntax correct here.
How can I fix my code so that it creates individual burned rasters for each polygon in the shapefile where output raster files are numbered?