3

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?

1
  • Looks good to me, check my answer below. Changed a couple of things.
    – Binx
    Commented Dec 4, 2021 at 8:49

1 Answer 1

2

I changed a couple of things:

Replaced polygon_ID with ['id']. That is how you call a column/attribute from a dataframe.

Added str(i) to your saving section to save the next polygon that is selected through your for loop.

import geopandas as gpd
from geocube.api.core import make_geocube

polygons = gpd.read_file('testing.shp')
polygon_IDs = polygons['id'].tolist()

for i in polygon_IDs:
    x = polygons.loc[polygons['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(str(i) + "_Output_Raster.tif")
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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