Python Rasterio – How to Rasterize by Attribute Using GDAL

gdalpythonrasterio

According to Rasterizing shapefiles with GDAL and Python? it seems that gdal allows rasterization of a layer according to a certain attribute

ds = gdal.RasterizeLayer(target_ds, [1], source_layer, options = ["ATTRIBUTE=ID"])

I would like to rasterize a layer with small square polygon geometries using rasterio

enter image description here

rasterio has a features.rasterize method (see docs), but it seems to only be able to output numpy arrays with 1's where the polygons occur. Since rasterio is a higher level library than gdal I am a bit surprised that selecting an attribute to burn the raster with is not supported functionality.

Is there any built-in method in rasterio to burn a raster by an attribute from the original vector layer?

Best Answer

The inputs to features.rasterize include

shapes (iterable of (geometry, value) pairs or iterable over) – geometries. geometry can either be an object that implements the geo interface or GeoJSON-like object.

So you can just pass tuples of (geom, value), where value is the attribute value you wish to burn into the raster.