[GIS] Problem in setting dimension using rioxarray set_spatial_dims()

coordinate systempythonrioxarrayxarray

I am having trouble setting dimensions in a xarray object.
I have created a xarray object (data, lats, and lons are 2D ndarray) and set a coordinate system as follows, and it is working.

da0 = xr.DataArray(
      data = data,
      dims = ["x","y"],
      coords = dict(
            lon = (["x","y"], lons),
            lat = (["x","y"], lats)
      )
)
da = da0.rio.write_crs("epsg:4326", inplace=True)

However, when I tried to set the spatial dimension for reprojection

da.rio.set_spatial_dims("lon", "lat", inplace=True)

it raises the following error.

   raise DimensionError(
rioxarray.exceptions.DimensionError: x dimension (lon) not found.

Why "lon" is not found although "da" has "lon"?
I want to set dimensions for using xr.rio.reproject() in the end.

Best Answer

Your dims and coords need to have the same name. This should work:

da0 = xr.DataArray(
      data = data,
      dims = ["x","y"],
      coords = dict(
            x = (["x","y"], lons),
            y = (["x","y"], lats)
      )
)
da = da0.rio.write_crs("epsg:4326", inplace=True)
Related Question