4

Given a random raster tif file, I want to set all cells which have a value of 0, to 'no data' using Python/rasterio. I just cant seem to find documentation about this simple operation.

import rasterio

src = rasterio.open('some_grid.tif')
...........

With R's raster package, with which I'm way more literate, I would perform this operation like this:

library(raster)

rast <- raster('some_grid.tif')
rast[rast == 0] <- NA
mcdesign
  • 105
  • 1
  • 6

1 Answers1

10

Similar syntax in Python, first read in the tif file to a numpy array. array==0 produces a boolean array, which can then be used as an index mask for setting the desired values to NAN.

import rasterio
import numpy as np

with rasterio.open('some_grid.tif') as src:
    array = src.read(1)

array[array==0] = np.nan
Christoph Rieke
  • 707
  • 5
  • 7
  • Could you add a little more context and explanation to your answer? A code-only answer is not as useful as an answer which explains what this code does. That way it can also help future readers. – Ralf Jun 03 '19 at 13:12
  • Thanks, added some description of the masking process. – Christoph Rieke Jun 03 '19 at 13:18
  • 1
    But in the case of integer datatype raster, the error, `ValueError: cannot convert float NaN to integer` will occur. – dhiraj Jul 09 '21 at 07:56