Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,9 @@ Deprecations
Bug Fixes
~~~~~~~~~

- Fix :py:meth:`DataArray.sortby` and :py:meth:`Dataset.sortby` raising ``KeyError``
when passing a tuple of dimension names, e.g. ``da.sortby(da.dims)`` (:issue:`4821`).
By `Timothy Hodson <https://github.com/thodson-usgs>`_.
- Fix multi-coordinate indexes being dropped in :py:meth:`DataArray._replace_maybe_drop_dims`
(e.g. after reducing over an unrelated dimension) and in :py:meth:`Dataset._copy_listed`
(e.g. when subsetting a Dataset by variable names). Both paths now consult
Expand Down
6 changes: 5 additions & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -8149,8 +8149,12 @@ def sortby(

if callable(variables):
variables = variables(self)
if not isinstance(variables, list):
if isinstance(variables, (str, DataArray)) or not isinstance(
variables, Iterable
):
variables = [variables]
else:
variables = list(variables)
arrays = [v if isinstance(v, DataArray) else self[v] for v in variables]
aligned_vars = align(self, *arrays, join="left")
aligned_self = cast("Self", aligned_vars[0])
Expand Down
5 changes: 5 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -4558,6 +4558,11 @@ def test_sortby(self) -> None:
actual = da.sortby(["x", "y"])
assert_equal(actual, expected)

# test tuple of dimension names (GH4821)
expected = sorted2d
actual = da.sortby(("x", "y"))
assert_equal(actual, expected)

@requires_bottleneck
def test_rank(self) -> None:
# floats
Expand Down
5 changes: 5 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -7323,6 +7323,11 @@ def test_sortby(self) -> None:
actual = ds.sortby(["x", "y"], ascending=False)
assert_equal(actual, ds)

# test tuple of dimension names (GH4821)
expected = sorted2d
actual = ds.sortby(("x", "y"))
assert_equal(actual, expected)

def test_sortby_descending_nans(self) -> None:
# Regression test for https://github.com/pydata/xarray/issues/7358
# NaN values should remain at the end when sorting in descending order
Expand Down
Loading