Skip to content

Inconsistent behavior of xarray.where for coordinate attributes #10982

@peanutfun

Description

@peanutfun

What happened?

Coordinate attributes of parameter cond are preserved when using keep_attrs=False, and not preserved when using keep_attrs=True. This is confusing. Furthermore, with the same setting, the attributes of cond are not preserved anymore as soon as parameter x also has coordinate attributes. I noticed this issue with the recent change to the default keep_attrs=True, but it does not seem to be related.

I am using xarray with geospatial plugins like rioxarray and odc-geo. These attach coordinate reference system information as attributes to coordinates. For my use case it is important to keep these attributes around. It seems to me like there is currently no way to ensure that this information is passed consistently through xr.where.

>>> arr = xr.DataArray(
>>>     rng.integers(0, 3, (3, 3)), coords={"a": np.arange(3), "b": np.arange(3)}
>>> )
>>> arr["a"].attrs = {"foo": "bar", "baz": 1}
>>> ds = xr.Dataset({"arr": arr})

>>> xr.where(ds > 1, 1.0, 0.0, keep_attrs=True)["a"].attrs
{}  # From `x`
>>> xr.where(ds > 1, 1.0, 0.0, keep_attrs=False)["a"].attrs
{"foo": "bar", "baz": 1}  # From `cond`

# With mirrored attributes in `x`, the behavior changes:
>>> ones = xr.ones_like(ds)
>>> ones["a"].attrs
{"foo": "bar", "baz": 1}

>>> xr.where(ds > 1, ones, 0.0, keep_attrs=True)["a"].attrs
{"foo": "bar", "baz": 1}  # From `x`
>>> xr.where(ds > 1, ones, 0.0, keep_attrs=False)["a"].attrs
{}  # ???

What did you expect to happen?

>>> xr.where(ds > 1, 1.0, 0.0, keep_attrs=True)["a"].attrs
{"foo": "bar", "baz": 1}
>>> xr.where(ds > 1, 1.0, 0.0, keep_attrs=False)["a"].attrs
{}
>>> xr.where(ds > 1, ones, 0.0, keep_attrs=True)["a"].attrs
{"foo": "bar", "baz": 1}
>>> xr.where(ds > 1, ones, 0.0, keep_attrs=False)["a"].attrs
{}

Minimal Complete Verifiable Example

# /// script
# requires-python = ">=3.11"
# dependencies = [
#   "xarray[complete]@git+https://github.com/pydata/xarray.git@main",
#   "numpy",
# ]
# ///
#
# This script automatically imports the development branch of xarray to check for issues.
# Please delete this header if you have _not_ tested this script with `uv run`!

import xarray as xr
import numpy as np
xr.show_versions()

rng = np.random.default_rng(1)
arr = xr.DataArray(
    rng.integers(0, 3, (3, 3)), coords={"a": np.arange(3), "b": np.arange(3)}
)
arr["a"].attrs = {"foo": "bar", "baz": 1}
ds = xr.Dataset({"arr": arr})

print(xr.where(ds > 1, 1.0, 0.0, keep_attrs=True)["a"].attrs)
print(xr.where(ds > 1, 1.0, 0.0, keep_attrs=False)["a"].attrs)

ones = xr.ones_like(ds)
print(xr.where(ds > 1, ones, 0.0, keep_attrs=True)["a"].attrs)
print(xr.where(ds > 1, ones, 0.0, keep_attrs=False)["a"].attrs)

Steps to reproduce

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.
  • Recent environment — the issue occurs with the latest version of xarray and its dependencies.

Relevant log output

Anything else we need to know?

No response

Environment

Package Version Editable project location ------------------------- ----------- ---------------------------------------- affine 2.4.0 anyio 4.12.0 appnope 0.1.4 argon2-cffi 25.1.0 argon2-cffi-bindings 25.1.0 arrow 1.4.0 asttokens 3.0.1 async-lru 2.0.5 attrs 25.4.0 babel 2.17.0 beautifulsoup4 4.14.3 bleach 6.3.0 build 1.3.0 cachetools 6.2.2 cartopy 0.25.0 certifi 2025.11.12 cffi 2.0.0 charset-normalizer 3.4.4 click 8.3.1 click-plugins 1.1.1.2 cligj 0.7.2 cloudpickle 3.1.2 comm 0.2.3 contourpy 1.3.3 cycler 0.12.1 dask 2025.11.0 debugpy 1.8.17 decorator 5.2.1 defusedxml 0.7.1 distributed 2025.11.0 executing 2.2.1 fastjsonschema 2.21.2 fonttools 4.61.0 fqdn 1.5.1 fsspec 2025.12.0 geopandas 1.1.1 h11 0.16.0 httpcore 1.0.9 httpx 0.28.1 hypothesis 6.148.7 idna 3.11 iniconfig 2.3.0 ipykernel 7.1.0 ipython 9.8.0 ipython-pygments-lexers 1.1.1 isoduration 20.11.0 jedi 0.19.2 jinja2 3.1.6 json5 0.12.1 jsonpointer 3.0.0 jsonschema 4.25.1 jsonschema-specifications 2025.9.1 jupyter-client 8.6.3 jupyter-core 5.9.1 jupyter-events 0.12.0 jupyter-lsp 2.3.0 jupyter-server 2.17.0 jupyter-server-terminals 0.5.3 jupyterlab 4.5.0 jupyterlab-pygments 0.3.0 jupyterlab-server 2.28.0 kiwisolver 1.4.9 lark 1.3.1 llvmlite 0.45.1 locket 1.0.0 markupsafe 3.0.3 matplotlib 3.10.7 matplotlib-inline 0.2.1 mistune 3.1.4 msgpack 1.1.2 nbclient 0.10.2 nbconvert 7.16.6 nbformat 5.10.4 nest-asyncio 1.6.0 notebook 7.5.0 notebook-shim 0.2.4 numba 0.62.1 numpy 2.3.5 odc-geo 0.4.10 packaging 25.0 pandas 2.3.3 pandocfilters 1.5.1 parso 0.8.5 partd 1.4.2 pexpect 4.9.0 pillow 12.0.0 pip 25.3 pip-tools 7.5.2 platformdirs 4.5.0 pluggy 1.6.0 prometheus-client 0.23.1 prompt-toolkit 3.0.52 psutil 7.1.3 ptyprocess 0.7.0 pure-eval 0.2.3 pycparser 2.23 pygments 2.19.2 pyogrio 0.12.1 pyparsing 3.2.5 pyproj 3.7.2 pyproject-hooks 1.2.0 pyshp 3.0.3 pytest 9.0.1 python-dateutil 2.9.0.post0 python-json-logger 4.0.0 pytz 2025.2 pyyaml 6.0.3 pyzmq 27.1.0 rasterio 1.4.3 referencing 0.37.0 requests 2.32.5 rfc3339-validator 0.1.4 rfc3986-validator 0.1.1 rfc3987-syntax 1.1.0 rioxarray 0.20.0 rpds-py 0.30.0 ruff 0.14.8 send2trash 1.8.3 setuptools 80.9.0 shapely 2.1.2 six 1.17.0 sortedcontainers 2.4.0 soupsieve 2.8 sparse 0.17.0 stack-data 0.6.3 tblib 3.2.2 terminado 0.18.1 tinycss2 1.4.0 tol-colors 2.1.0 toolz 1.1.0 tornado 6.5.2 traitlets 5.14.3 typing-extensions 4.15.0 tzdata 2025.2 uri-template 1.3.0 urllib3 2.5.0 wcwidth 0.2.14 webcolors 25.10.0 webencodings 0.5.1 websocket-client 1.9.0 wheel 0.45.1 xarray 2025.11.0 zict 3.0.0 ```

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions