Wednesday, 3 November 2021

xarray transpose doesn't sort the dimensions of an xr.Dataset

I would like to sort the dimensions of an xarray Dataset in alphabetical order. I am using ds.transpose(*sorted(ds.dims)). This seems to sort the coordinates/dimensions of each DataArray in the Dataset, but not the coordinates of the Dataset itself.

Example:

    ds = xr.Dataset(
    {
        'z': (['c', 'a', 'b'], np.ones(shape=(2, 2, 2))),
        'x': (['a', 'b', 'c'], np.zeros(shape=(2, 2, 2))),
        'y': (['c'], [0, 1]),
    },
    coords={'c': [30, 31], 'a': [10, 11], 'b': [20, 21]}
)

    ds.transpose('a', 'b', 'c')

    <xarray.Dataset>
Dimensions:  (c: 2, a: 2, b: 2)
Coordinates:
  * c        (c) int64 30 31
  * a        (a) int64 10 11
  * b        (b) int64 20 21
Data variables:
    z        (a, b, c) float64 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
    x        (a, b, c) float64 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
    y        (c) int64 0 1

Expected behaviour is that the coordinates and dimensions of the entire xr.Dataset would be sorted as 'a', 'b', 'c'. However, you can see that only the dimensions of the data variables themselves are in this order.

Any help is deeply appreciated, thank you!



from xarray transpose doesn't sort the dimensions of an xr.Dataset

No comments:

Post a Comment