This answer is a direct solution to your stated problem.
As an alternate approach to using assign_coords - it appears what you have is a dataset with dimensions without coordinates (lat, lon)
, and non-indexing coordinates xlat (lat)
and xlon (lon)
giving the actual lat/lon values. This is a really common situation when reading netCDF data.
I imagine your data looks something like this:
In [3]: ds = xr.Dataset(
...: {'wrfout_tsk_tavg': (('lat', 'lon'), np.random.random((4, 8)))},
...: coords={
...: 'xlat': (('lat', ), np.arange(23, 27)),
...: 'xlon': (('lon', ), np.arange(-110, -102)),
...: },
...: )
In [4]: ds
Out[4]:
<xarray.Dataset>
Dimensions: (lat: 4, lon: 8)
Coordinates:
xlat (lat) int64 23 24 25 26
xlon (lon) int64 -110 -109 -108 -107 -106 -105 -104 -103
Dimensions without coordinates: lat, lon
Data variables:
wrfout_tsk_tavg (lat, lon) float64 0.4214 0.5839 0.6675 ... 0.4333 0.4409
You can use xr.DataArray.swap_dims
or xr.Dataset.swap_dims
to switch between indexing and non-indexing coordinates with the same dimensionality. In your case:
In [5]: ds = ds.swap_dims({"lat": "xlat", "lon": "xlon"})
...: ds
Out[5]:
<xarray.Dataset>
Dimensions: (xlat: 4, xlon: 8)
Coordinates:
* xlat (xlat) int64 23 24 25 26
* xlon (xlon) int64 -110 -109 -108 -107 -106 -105 -104 -103
Data variables:
wrfout_tsk_tavg (xlat, xlon) float64 0.4214 0.5839 0.6675 ... 0.4333 0.4409