1

When reading a raster dataset with rasterio 1.3.3, nodata values are replaced by nan.

How to read the raster dataset so that nodata cells are having their true value in the resulting numpy array from the .read() method?

import rasterio

src = rasterio.open(
    input_file_path,
    mode = 'r',
    driver = 'GTiff',
    count = None,
    crs = 'EPSG:2056',
    transform = None,
    dtype = 'float32',
)

data = src.read()

data # <- print an array with 'nan' in cells with nodata.
src.nodata # <- prints -9999.0

I'd like an array where nodata cells equal -9999.0.

1
  • Why do you specify driver, count, crs, transform & dtype when reading? It's not needed.
    – user2856
    Commented Oct 29, 2022 at 22:52

2 Answers 2

1

I can't reproduce. Given a raster where src.nodata is -9999.0 and actually has -9999.0 values in the dataset, reading the data as a numpy array gives -9999.0 as expected with rasterio 1.3.3.

You will however, get nan values if they are stored in the dataset. Specifying dst.nodata = -9999.0 when you write the array to file will not change those nan values, nor will it make rasterio magically change them to -9999.0 when you read the data.

If you have nans in your data, either change them to the required nodata value before you write it out, or when you read it back:

# Before writing
data[np.isnan(data)] = dst.nodata
dst.write(data)

# Or after reading
data = src.read()
data[np.isnan(data)] = src.nodata
1

In addition to the answer from user2856, another approach is to read the data as a masked array and then fill the masked values with the nodata value.

with rasterio.open(input_file_path, mode="r") as src:
    data_masked = src.read(masked=True)
    nodata_value = src.nodata

data = data_masked.filled(nodata_value) 

I highly recommend to open the file with a context manager as it ensures that the file is closed properly and is just cleaner without a 'src.close()' at the end of the function.

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.