xarray: Error when supplying a tuple of dimensions to DataArray.sortby()

What happened:

A KeyError is thrown when supplying a tuple of dimensions to DataArray.sortby()

What you expected to happen:

The dataarray to be sorted according to the dimensions.

Minimal Complete Verifiable Example:

import xarray as xr
import numpy as np

da=xr.DataArray(np.random.rand(3,3), coords=(('x', range(3, 0, -1)), ('y', range(3, 0, -1))))
da.sortby(da.dims)

Anything else we need to know?:

If the tuple is cast to a list it works correctly:

da.sortby(list(da.dims))

Environment:

Output of <tt>xr.show_versions()</tt>

INSTALLED VERSIONS

commit: None python: 3.6.12 (default, Nov 11 2020, 22:22:08) [GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.46.4)] python-bits: 64 OS: Darwin OS-release: 18.7.0 machine: x86_64 processor: i386 byteorder: little LC_ALL: None LANG: None LOCALE: en_US.UTF-8 libhdf5: None libnetcdf: None

xarray: 0.16.2 pandas: 1.1.4 numpy: 1.19.4 scipy: 1.5.4 netCDF4: None pydap: None h5netcdf: None h5py: None Nio: None zarr: None cftime: None nc_time_axis: None PseudoNetCDF: None rasterio: None cfgrib: None iris: None bottleneck: 1.3.2 dask: 2020.12.0 distributed: None matplotlib: 3.3.3 cartopy: None seaborn: None numbagg: None pint: None setuptools: 50.3.2 pip: 20.3.3 conda: None pytest: 6.2.1 IPython: 7.16.1 sphinx: None

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Comments: 18 (8 by maintainers)

Most upvoted comments

here’s an example:

In [2]: xr.Dataset({"a": ([("a", "b")], [1])})
Out[2]: 
<xarray.Dataset>
Dimensions:  (('a', 'b'): 1)
Dimensions without coordinates: ('a', 'b')
Data variables:
    a        (('a', 'b')) int64 1

If you allow explicitly tuple, doesn’t it mean I need to edit this part

Yes!

(I find it a little bit weird to give dimensions in list, no ? I thought that generally tuples were more adapted to provide dims)

Yes, I feel similarly. For one xr.Dataset(dict(var=(('a','b'), np.random.rand(3)))) is an error, rather than a one-dimensioned dataset with a single dim called ('a','b'). But OTOH I can very much empathize with accepting any Hashable for dim names most functions, which includes tuples. So I am fine formalizing this (apart from the constructor).

Can you tell me which test-case I can implement to fulfill all the requirements needed ? I can’t think of test cases that I can implement except the one suggested first, and that one passes with the first modification

How about a test that checks the example above suggests a list, rather than raising a vanilla KeyError?

Cheers @thomashirtz