[GIS] Open a mutliband raster, edit values in one of the bands, and overwrite the raster using Python/Rasterio

editingmulti-bandpythonrasterio

I have numerous multiband rasters (36 band) in which preserving the band order is important for future processing. One of the bands often contains erroneous data and I'd like to be able to change all the values in within that band to 0, but keep the band in place. Then ideally overwrite the changes to the existing raster. Is there a way to do this without having to open the band in question, make the change to 0, and then re-stack all the other bands along with the edited band into a new file? Or at the very least save the changes to a new raster without having to call up the other 35 bands individually into the stacking function?

For instance

import rasterio as rio
import numpy as np

inraster = "path_to_a_mutliband_raster"
rast = rio.open(inraster)
badband = rast.read(7)
badbad[badband != 0] = 0

From there I'm not sure how to save those changes back into the mutliband raster.

Best Answer

You can write to selected bands using the indexes keyword.

If you want your array to contain only zeros you can also create a new numpy array. This way you don't need to read any data at all.

import rasterio as rio
import numpy as np

with rio.open ("/src.tif", "w") as img:
    band = np.zeros(shape=(img.width, img.height), dtype=img.dtype)

    img.write (band, indexes = 7)