Skip to content

Using where without keep_attrs=True removes attrs stored in coordinates on the inputs #8480

@CarlAndersson

Description

@CarlAndersson

What happened?

Sometimes I store info about coordinates in the attributes on the coordinate. It's useful for stuff like units or resolutions.
I noticed that these attributes can go missing from DataArrays that are used as the input to xr.where, which is a somewhat unexpected side-effect.

What did you expect to happen?

The input DataArray is left unmodified by xr.where.

Minimal Complete Verifiable Example

import xarray as xr
import numpy as np

values = xr.DataArray(np.linspace(0, 2), dims='x')
values = values.assign_coords(x=values.x.assign_attrs(attr=10))
print('attr' in values.x.attrs)  # True
nonzero = values != 0
print('attr' in values.x.attrs)  # True
xr.where(nonzero, values, np.nan, keep_attrs=False)
print('attr' in values.x.attrs)  # False

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

No response

Anything else we need to know?

No response

Environment

Details INSTALLED VERSIONS ------------------ commit: None python: 3.11.0 | packaged by conda-forge | (main, Oct 25 2022, 06:09:06) [MSC v.1929 64 bit (AMD64)] python-bits: 64 OS: Windows OS-release: 10 machine: AMD64 processor: Intel64 Family 6 Model 142 Stepping 12, GenuineIntel byteorder: little LC_ALL: None LANG: None LOCALE: ('Swedish_Sweden', '1252') libhdf5: None libnetcdf: None

xarray: 2023.11.0
pandas: 1.5.1
numpy: 1.23.4
scipy: 1.9.3
netCDF4: None
pydap: None
h5netcdf: None
h5py: None
Nio: None
zarr: None
cftime: None
nc_time_axis: None
iris: None
bottleneck: None
dask: None
distributed: None
matplotlib: None
cartopy: None
seaborn: None
numbagg: None
fsspec: None
cupy: None
pint: None
sparse: None
flox: None
numpy_groupies: None
setuptools: 65.5.1
pip: 22.3.1
conda: None
pytest: None
mypy: None
IPython: 8.6.0
sphinx: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugneeds triageIssue that has not been reviewed by xarray team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions