Sadly there is no direct way to use your GeoDataFrame in gdal's Rasterize function.
In the GDAL/OGR cookbook there's an example on how to perform this by reading a Vector layer from your disk.
Original example from the GDAL/OGR Cookbook
from osgeo import gdal, ogr
# Define pixel_size and NoData value of new raster
pixel_size = 25
NoData_value = -9999
# Filename of input OGR file
vector_fn = 'test.shp'
# Filename of the raster Tiff that will be created
raster_fn = 'test.tif'
# Open the data source and read in the extent
source_ds = ogr.Open(vector_fn)
source_layer = source_ds.GetLayer()
x_min, x_max, y_min, y_max = source_layer.GetExtent()
# Create the destination data source
x_res = int((x_max - x_min) / pixel_size)
y_res = int((y_max - y_min) / pixel_size)
target_ds = gdal.GetDriverByName('GTiff').Create(raster_fn, x_res, y_res, 1, gdal.GDT_Byte)
target_ds.SetGeoTransform((x_min, pixel_size, 0, y_max, 0, -pixel_size))
band = target_ds.GetRasterBand(1)
band.SetNoDataValue(NoData_value)
# Rasterize
gdal.RasterizeLayer(target_ds, [1], source_layer, burn_values=[0]))
If you want to rasterize data that you have stored in a GeoPandas GeoDataFrame, you'll have to write it to disk first. Here's a modified version of the code above that assumes you want to rasterize the contents of a GeoDataFrame called source_gdf
.
Modified example from the GDAL/OGR Cookbook using GeoPandas GeoDataFrame
# I'm assuming that `source_gdf` has already been populated with geodata.
# The only thing we're doing is exporting the contents of `source_gdf` to disk.
source_gdf_fname = '/path/to/file/output.gpkg'
source_gdf_layername = 'source_gdf'
source_gdf.to_file(source_gdf_fname, layer=source_gdf_layername, driver='GPKG')
from osgeo import gdal, ogr
# Define pixel_size and NoData value of new raster
pixel_size = 25
NoData_value = -9999
# Filename of input OGR file
vector_fn = 'test.shp'
# Filename of the raster Tiff that will be created
raster_fn = 'test.tif'
# Open the data source and read in the extent
# The only change to the code here is that I point to the file
# and layer we just created at the top of the code. The rest of the
# code snippet is identical to the last.
source_ds = ogr.Open(source_gdf_fname)
source_layer = source_ds.GetLayer(source_gdf_layername)
x_min, x_max, y_min, y_max = source_layer.GetExtent()
# Create the destination data source
x_res = int((x_max - x_min) / pixel_size)
y_res = int((y_max - y_min) / pixel_size)
target_ds = gdal.GetDriverByName('GTiff').Create(raster_fn, x_res, y_res, 1, gdal.GDT_Byte)
target_ds.SetGeoTransform((x_min, pixel_size, 0, y_max, 0, -pixel_size))
band = target_ds.GetRasterBand(1)
band.SetNoDataValue(NoData_value)
# Rasterize
gdal.RasterizeLayer(target_ds, [1], source_layer, burn_values=[0]))