I need a function that takes a dataarray and replaces a dimension with a coordinate from a different dataset. I would like some advice on the best way to do this.
Performance is important, and checking is not. I want to bypass all reindexing, aligning, etc and operate at a low level.
Here's what I have now. I'm sure there is a better way.
def _replace_dim(da, olddim, newdim):
"""Replace a dimension with a new dimension
PARAMETERS
----------
da : xarray.DataArray
olddim : str
name of the dimension to replace
newdim : xarray.DataArray
dimension to replace it with
RETURNS
-------
da_new : xarray.DataArray
"""
# get a dictionary of coords
# can't use da.coords because it is an immutable
# xarray.core.coordinates.DataArrayCoordinates object
coords = {dim: da[dim] for dim in da.dims}
# add the new dimension to it
# delete the old dimension
del coords[olddim]
# redefine dims
dims = list(da.dims)
# define a new dataset
return xr.DataArray(da.data, coords, dims)