1

I have used xarray to open the netcdf file, and using rioxarray exported the raster as a .tif file. However, the exported raster doesn't have definition for nodata value, and hence, the GIS software such as ArcGIS, or QGIS cannot recognize the NoData. I could reclassify it in arcGIS afterwards, but later I need to implement this on large number of datasets, so automation is preferred. How can we define nodata while exporting raster?

Here is my code sample:

  ds_mask = xr.open_dataset(path_mask)
  nodata_value = np.nan
  ds_mask = xr.where(ds_mask == 0, nodata_value, ds_mask)
  ds_mask = coordAssign(ds_mask)

  mask_filename = f"/content/LANDMASK/landmask1.tif"
  ds_mask.rio.to_raster(mask_filename, nodata=np.nan)

Also, here is my implementation function to assign the coordinates:

def coordAssign(xrData):
    # convert longitude from (0-360) to (-180 to 180) (if required)
    xrData['lon'] = (xrData['lon'] + 180) % 360 - 180
    xrData = xrData.sortby(xrData.lon)
    xrData = xrData.rio.set_spatial_dims('lon', 'lat')
    # print(data.rio.crs)
    xrData.rio.set_crs("epsg:4326")
    return xrData

Find the image for your reference, while clicking on masked region, the ArcGIS should recognize it as NoData but at this time it's set to nan. enter image description here

1 Answer 1

2

Documentation reference:

Summary: You can lose metadata after performing xarray operations and you have to be careful to manage it.

Methods to use before/after xarray operations:

  • rio.nodata
  • rio.write_nodata

Example:

nodata = raster.rio.nodata

raster = raster.where(raster != nodata)

raster.rio.write_nodata(nodata, encoded=True, inplace=True)

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