add dimension to an xarray DataArray
Because of the way that math is applied over new dimensions I like to multiply in order to add new dimensions.
identityb = xr.DataArray(np.ones_like(b_coords), coords=[('b', b_coords)])
y = x * identityb
With reference to the syntax of the question:
y = x.expand_dims({"b": b_coords})
Using .assign_coords
method will do it. However you can't assign coordinates to a non-existant dimension, the way to do as a one liner is:
y = x.expand_dims({b_coords.name: b_size}).assign_coords({b_coords.name: b_coords})
If DA
is your data array with length DimLen
, you can now use expand_dims
:
DA.expand_dims({'NewDim':DimLen})