Skip to content

Commit 8e362ee

Browse files
thodson-usgsclaude
andcommitted
Fix sortby raising KeyError when passed a tuple of dimension names
Closes #4821 Co-authored-by: Claude <noreply@anthropic.com>
1 parent f7e47a1 commit 8e362ee

4 files changed

Lines changed: 18 additions & 1 deletion

File tree

‎doc/whats-new.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,9 @@ Deprecations
162162
Bug Fixes
163163
~~~~~~~~~
164164

165+
- Fix :py:meth:`DataArray.sortby` and :py:meth:`Dataset.sortby` raising ``KeyError``
166+
when passing a tuple of dimension names, e.g. ``da.sortby(da.dims)`` (:issue:`4821`).
167+
By `Timothy Hodson <https://github.com/thodson-usgs>`_.
165168
- Fix multi-coordinate indexes being dropped in :py:meth:`DataArray._replace_maybe_drop_dims`
166169
(e.g. after reducing over an unrelated dimension) and in :py:meth:`Dataset._copy_listed`
167170
(e.g. when subsetting a Dataset by variable names). Both paths now consult

‎xarray/core/dataset.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8149,8 +8149,12 @@ def sortby(
81498149

81508150
if callable(variables):
81518151
variables = variables(self)
8152-
if not isinstance(variables, list):
8152+
if isinstance(variables, (str, DataArray)) or not isinstance(
8153+
variables, Iterable
8154+
):
81538155
variables = [variables]
8156+
else:
8157+
variables = list(variables)
81548158
arrays = [v if isinstance(v, DataArray) else self[v] for v in variables]
81558159
aligned_vars = align(self, *arrays, join="left")
81568160
aligned_self = cast("Self", aligned_vars[0])

‎xarray/tests/test_dataarray.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4558,6 +4558,11 @@ def test_sortby(self) -> None:
45584558
actual = da.sortby(["x", "y"])
45594559
assert_equal(actual, expected)
45604560

4561+
# test tuple of dimension names (GH4821)
4562+
expected = sorted2d
4563+
actual = da.sortby(("x", "y"))
4564+
assert_equal(actual, expected)
4565+
45614566
@requires_bottleneck
45624567
def test_rank(self) -> None:
45634568
# floats

‎xarray/tests/test_dataset.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7323,6 +7323,11 @@ def test_sortby(self) -> None:
73237323
actual = ds.sortby(["x", "y"], ascending=False)
73247324
assert_equal(actual, ds)
73257325

7326+
# test tuple of dimension names (GH4821)
7327+
expected = sorted2d
7328+
actual = ds.sortby(("x", "y"))
7329+
assert_equal(actual, expected)
7330+
73267331
def test_sortby_descending_nans(self) -> None:
73277332
# Regression test for https://github.com/pydata/xarray/issues/7358
73287333
# NaN values should remain at the end when sorting in descending order

0 commit comments

Comments
 (0)