Dears, I need to create a xarray.datarray with the names of the dimensions equal to the names of the coordinates, however, I am not succeeding. Here is the code for reproduction:
import numpy as np
import xarray as xr
data = [[23, 22, 21],
[22, 20, 24]]
x, y = np.meshgrid([-45, -44, -43], [-21, -20])
t2m = xr.DataArray(data=data,
dims=["lon", "lat"],
coords=dict(
lon=(["lon", "lat"], x),
lat=(["lon", "lat"], y)))
With this code I get the following error:
MissingDimensionsError: 'lon' has more than 1-dimension and the same name as one of its dimensions ('lon', 'lat'). xarray disallows such variables because they conflict with the coordinates used to label dimensions.
To create the datarray without this error I would just change the name of the dimensions:
t2m = xr.DataArray(data=data,
dims=["x", "y"],
coords=dict(
lon=(["x", "y"], x),
lat=(["x", "y"], y)))
However, I would like to use the .sel method to extract values for certain coordinates, and that would only work if the dimension values were equal to the coordinates, for example:
t2.sel(lon=-45, lat=-21, method='nearest')
Could someone help me with this? The netCDF files I download from internet sources (such as Copernicus netCDF files with ERA5 reanalisys data) come with coordinate names equal to dimensions, and dimension values equal to coordinates values, thus allowing use the .sel() method to extract data for a given coordinate (lon ,lat).
Thank you very much in advance.