Skip to content

sortby descending does not handle nans correctly #7358

Open
@blackbox-tech

Description

@blackbox-tech

What happened?

sortby ascending=False just returns the reversed output of ascending=True
This is incorrect if the array contains nan values. (< is numerically not the opposite of > for nan values)

For example:

a = xr.DataArray([3, np.nan, 4, 2, np.nan], 
                 {"label": ["a", "b", "c", "d", "e"]})
a.sortby(a, ascending=False)

produces

[nan, nan,  4.,  3.,  2.]

What did you expect to happen?

Using the example above, I expect to see:

[ 4.,  3.,  2., nan, nan]

A workaround to return the correct result can be implemented like this:

idx = np.argpartition(-a, np.arange((np.isfinite(a)).sum())).values
a[idx]

Minimal Complete Verifiable Example

No response

MVCE confirmation

  • Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
  • Complete example — the example is self-contained, including all data and the text of any traceback.
  • Verifiable example — the example copy & pastes into an IPython prompt or Binder notebook, returning the result.
  • New issue — a search of GitHub Issues suggests this is not a duplicate.

Relevant log output

No response

Anything else we need to know?

No response

Environment

xarray                    2022.11.0       py310hecd8cb5_0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions