Skip to content

Commit 3b6cd2a

Browse files
slevangheadtr1ck
andauthored
Handle numpy-only attrs in xr.where (#7364)
* check if result has attrs before trying to add them * add whats new * Apply suggestions from code review Co-authored-by: Mick <[email protected]> Co-authored-by: Mick <[email protected]>
1 parent 7fc5022 commit 3b6cd2a

File tree

3 files changed

+8
-2
lines changed

3 files changed

+8
-2
lines changed

doc/whats-new.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ Deprecations
3434

3535
Bug fixes
3636
~~~~~~~~~
37-
37+
- Allow numpy-only objects in :py:func:`where` when ``keep_attrs=True`` (:issue:`7362`, :pull:`7364`).
38+
By `Sam Levang <https://github.com/slevang>`_.
3839

3940
Documentation
4041
~~~~~~~~~~~~~

xarray/core/computation.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1876,7 +1876,7 @@ def where(cond, x, y, keep_attrs=None):
18761876
# be consistent with the `where` method of `DataArray` and `Dataset`
18771877
# rebuild the attrs from x at each level of the output, which could be
18781878
# Dataset, DataArray, or Variable, and also handle coords
1879-
if keep_attrs is True:
1879+
if keep_attrs is True and hasattr(result, "attrs"):
18801880
if isinstance(y, Dataset) and not isinstance(x, Dataset):
18811881
# handle special case where x gets promoted to Dataset
18821882
result.attrs = {}

xarray/tests/test_computation.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1964,6 +1964,11 @@ def test_where_attrs() -> None:
19641964
expected["a"].attrs = {"attr": "x_coord"}
19651965
assert_identical(expected, actual)
19661966

1967+
# no xarray objects, handle no attrs
1968+
actual_np = xr.where(True, 0, 1, keep_attrs=True)
1969+
expected_np = np.array(0)
1970+
assert_identical(expected_np, actual_np)
1971+
19671972
# DataArray and 2 Datasets, takes attrs from x
19681973
ds_x = xr.Dataset(data_vars={"x": x}, attrs={"attr": "x_ds"})
19691974
ds_y = xr.Dataset(data_vars={"x": y}, attrs={"attr": "y_ds"})

0 commit comments

Comments
 (0)