Skip to content

Allow where to receive a callable #3827

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

Merged
merged 4 commits into from
Mar 7, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 xarray/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -1152,6 +1152,9 @@ def where(self, cond, other=dtypes.NA, drop: bool = False):
from .dataarray import DataArray
from .dataset import Dataset

if callable(cond):
return self.where(cond(self), other=other, drop=drop)

if drop:
if other is not dtypes.NA:
raise ValueError("cannot set `other` if drop=True")
Expand Down
6 changes: 6 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -2215,6 +2215,12 @@ def test_where(self):
actual = arr.where(arr.x < 2, drop=True)
assert_identical(actual, expected)

def test_where_lambda(self):
arr = DataArray(np.arange(4), dims="y")
expected = arr.sel(y=slice(2))
actual = arr.where(lambda x: x.y < 2, drop=True)
assert_identical(actual, expected)

def test_where_string(self):
array = DataArray(["a", "b"])
expected = DataArray(np.array(["a", np.nan], dtype=object))
Expand Down
9 changes: 9 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -4349,13 +4349,22 @@ def test_where(self):
assert actual.a.name == "a"
assert actual.a.attrs == ds.a.attrs

# lambda
ds = Dataset({"a": ("x", range(5))})
expected = Dataset({"a": ("x", [np.nan, np.nan, 2, 3, 4])})
actual = ds.where(lambda x: x > 1)
assert_identical(expected, actual)

def test_where_other(self):
ds = Dataset({"a": ("x", range(5))}, {"x": range(5)})
expected = Dataset({"a": ("x", [-1, -1, 2, 3, 4])}, {"x": range(5)})
actual = ds.where(ds > 1, -1)
assert_equal(expected, actual)
assert actual.a.dtype == int

actual = ds.where(lambda x: x > 1, -1)
assert_equal(expected, actual)

with raises_regex(ValueError, "cannot set"):
ds.where(ds > 1, other=0, drop=True)

Expand Down