Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bug when querying unnamed dataarray #5493

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
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
6 changes: 6 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ New Features
By `Thomas Hirtz <https://github.com/thomashirtz>`_.
- allow passing a function to ``combine_attrs`` (:pull:`4896`).
By `Justus Magin <https://github.com/keewis>`_.
- The values stored in an dataarray can now be referenced in a call to
py:func:`xarray.DataArray.query` via 'self' (:issue:`5492`, :pull:`5493`).
By `Tom Nicholas <https://github.com/TomNicholas>`_.

Breaking changes
~~~~~~~~~~~~~~~~
Expand Down Expand Up @@ -73,6 +76,9 @@ Bug fixes
- Fix the ``repr`` of :py:class:`Variable` objects with ``display_expand_data=True``
(:pull:`5406`)
By `Justus Magin <https://github.com/keewis>`_.
- Fixed :py:func:`xarray.DataArray.query` to not fail with an unnamed dataarray
(:issue:`5492`, :pull:`5493`).
By `Tom Nicholas <https://github.com/TomNicholas>`_.


Documentation
Expand Down
34 changes: 31 additions & 3 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -4437,6 +4437,8 @@ def query(
dimension(s), where the indexers are given as strings containing
Python expressions to be evaluated against the values in the array.

The values stored in dataarrays can also be referenced in queries as 'self'.

Parameters
----------
queries : dict, optional
Expand Down Expand Up @@ -4488,17 +4490,43 @@ def query(
<xarray.DataArray 'a' (x: 2)>
array([3, 4])
Dimensions without coordinates: x

>>> da = xr.DataArray(np.arange(0, 5, 1), dims="x", name=None)
>>> da
<xarray.DataArray (x: 5)>
array([0, 1, 2, 3, 4])
Dimensions without coordinates: x
>>> da.query(x="self > 2")
<xarray.DataArray (x: 2)>
array([3, 4])
Dimensions without coordinates: x
"""

ds = self._to_dataset_whole(shallow_copy=True)
ds = ds.query(
if self.name is None:
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line causes a mypy error

xarray/core/dataarray.py:4510: error: Incompatible types in assignment (expression has type "Hashable", variable has type "str")  [assignment]
Found 1 error in 1 file (checked 142 source files)

# Naming unnamed dataarrays as 'self' allows querying their values still
name = "self"
else:
# For consistency allow named datarrays to be referred to as 'self' also
name = self.name
queries = either_dict_or_kwargs(queries, queries_kwargs, "query")
queries = {
d: (q.replace("self", name) if isinstance(q, str) else q)
for d, q in queries.items()
}
queries_kwargs = {}

ds = self._to_dataset_whole(name=name).query(
queries=queries,
parser=parser,
engine=engine,
missing_dims=missing_dims,
**queries_kwargs,
)
return ds[self.name]

da = ds[name]
if name == "self":
da.name = None
return da

def curvefit(
self,
Expand Down
14 changes: 14 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -4659,6 +4659,8 @@ def test_query(self, backend, engine, parser):
bb = DataArray(data=b, dims=["x"], name="b")
cc = DataArray(data=c, dims=["y"], name="c")
dd = DataArray(data=d, dims=["z"], name="d")
nn = DataArray(data=a, dims=["x"])
nn.name = None

elif backend == "dask":
import dask.array as da
Expand All @@ -4667,6 +4669,8 @@ def test_query(self, backend, engine, parser):
bb = DataArray(data=da.from_array(b, chunks=3), dims=["x"], name="b")
cc = DataArray(data=da.from_array(c, chunks=7), dims=["y"], name="c")
dd = DataArray(data=da.from_array(d, chunks=12), dims=["z"], name="d")
nn = DataArray(data=da.from_array(a, chunks=3), dims=["x"])
nn.name = None

# query single dim, single variable
actual = aa.query(x="a > 5", engine=engine, parser=parser)
Expand Down Expand Up @@ -4704,6 +4708,16 @@ def test_query(self, backend, engine, parser):
with pytest.raises(UndefinedVariableError):
aa.query(x="spam > 50") # name not present

# test with nameless dataarray (GH issue 5492)
actual = nn.query(x="self > 5", engine=engine, parser=parser)
expect = nn.isel(x=(nn > 5))
assert_identical(expect, actual)

# test referring to named dataarray as self
actual = aa.query(x="self > 5", engine=engine, parser=parser)
expect = aa.isel(x=(aa > 5))
assert_identical(expect, actual)

@requires_scipy
@pytest.mark.parametrize("use_dask", [True, False])
def test_curvefit(self, use_dask):
Expand Down