1

I'm trying to subtract one raster from another. They have a slightly different shape/extend but the same CRS/resolution. While attempting to subtract the raster, I received this error: 'zero-size array to reduction operation minimum which has no identity.' The shape of the main raster is (15078, 7279) and the shape of the second raster is (13162, 5255). I'm able to subtract the rasters using QGIS.

What options do I have to overcome this error? My second raster is small since I'm only interested in the extend covered by the second raster.

import rioxarray as rxr
main_raster = rxr.open_rasterio(raster_to_subtract_from, masked=True).squeeze()
second_raster = rxr.open_rasterio(subtracting_raster, masked=True).squeeze()
difference = main_raster - second_raster

Though the title/error is similar, this question is not the same as this question.

Error trace:

  File "C:\Dev\**\venv\lib\site-packages\rioxarray\_io.py", line 265, in _get_indexer
    start, stop = np.min(ikey), np.max(ikey) + 1
  File "<__array_function__ internals>", line 5, in amin
  File "C:\Dev\**\venv\lib\site-packages\numpy\core\fromnumeric.py", line 2879, in amin
    return _wrapreduction(a, np.minimum, 'min', axis, None, out,
  File "C:\Dev\**\venv\lib\site-packages\numpy\core\fromnumeric.py", line 86, in _wrapreduction
    return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
ValueError: zero-size array to reduction operation minimum which has no identity

1 Answer 1

3

They need to have the same shape/resolution/crs to do raster math. You can do this with rio.reproject_match: https://corteva.github.io/rioxarray/stable/examples/reproject_match.html

import rioxarray as rxr
main_raster = rxr.open_rasterio(raster_to_subtract_from, masked=True).squeeze()
second_raster = rxr.open_rasterio(subtracting_raster, masked=True).squeeze()
second_raster_match = second_raster.rio.reproject_match(main_raster)

This may also be necessary: https://github.com/corteva/rioxarray/issues/298

second_raster_match = second_raster_match.assign_coords({
    "x": main_raster.x,
    "y": main_raster.y,
})

Finally:

difference = main_raster - second_raster_match
2
  • Thanks! Your answer helped me address the error.
    – PPR
    Aug 31, 2021 at 1:16
  • Perfect, I am glad to hear that it worked!
    – snowman2
    Aug 31, 2021 at 1:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.