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.

  • I am not certain at all, but I would be surprised if it would be possible to edit only a single band without re-writing the full file. One somewhat messy workaround I can think of would be to write your 0-band to disk, then make a virtual raster that stacks the good bands before, the 0-band, and the good bands after into a single file.
    – Jon
    Commented Apr 8, 2019 at 16:30

2 Answers 2


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)
  • Does this preserve projection info within the tif?
    – zabop
    Commented Jun 13, 2022 at 7:27
  • @zabop I think it does if you open in "r+" mode, not "w" mode.
    – jesnes
    Commented Jul 20, 2022 at 23:08

I did not find a solution to overwrite the existing raster, but the time of making a new one was much faster than I expected. In this case it still required calling up the other bands and writing them back to new file. Here is what I used -

import rasterio as rio
import numpy as np

rasterin = "path_to_a_mutliband_raster"
rasterout = 'path_to_output_raster'

rast = rio.open(rasterin)
meta = rast.meta
bands = [x + 1 for x in list(range(rast.count))]
badbands = [7, 16, 25]

with rio.open(rasterout, 'w', **meta) as dst:
    with rio.open(rasterin) as src:
        for ID, b in enumerate(bands,1):
            if b in ndvibands:
                ndvi = src.read(b)
                ndvi[ndvi != 0] = 0
                dst.write(ndvi, ID)
                data = src.read(b)
                dst.write(data, ID)

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.