πΎ Xarray is now 10 years old! π

# xarray.where#

xarray.where(cond, x, y, keep_attrs=None)[source]#

Return elements from x or y depending on cond.

Performs xarray-like broadcasting across input arguments.

All dimension coordinates on x and y must be aligned with each other and with cond.

Parameters:
Returns:

`Dataset`, `DataArray`, `Variable` or array β In priority order: Dataset, DataArray, Variable or array, whichever type appears as an input argument.

Examples

```>>> x = xr.DataArray(
...     0.1 * np.arange(10),
...     dims=["lat"],
...     coords={"lat": np.arange(10)},
...     name="sst",
... )
>>> x
<xarray.DataArray 'sst' (lat: 10)>
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
Coordinates:
* lat      (lat) int64 0 1 2 3 4 5 6 7 8 9
```
```>>> xr.where(x < 0.5, x, x * 100)
<xarray.DataArray 'sst' (lat: 10)>
array([ 0. ,  0.1,  0.2,  0.3,  0.4, 50. , 60. , 70. , 80. , 90. ])
Coordinates:
* lat      (lat) int64 0 1 2 3 4 5 6 7 8 9
```
```>>> y = xr.DataArray(
...     0.1 * np.arange(9).reshape(3, 3),
...     dims=["lat", "lon"],
...     coords={"lat": np.arange(3), "lon": 10 + np.arange(3)},
...     name="sst",
... )
>>> y
<xarray.DataArray 'sst' (lat: 3, lon: 3)>
array([[0. , 0.1, 0.2],
[0.3, 0.4, 0.5],
[0.6, 0.7, 0.8]])
Coordinates:
* lat      (lat) int64 0 1 2
* lon      (lon) int64 10 11 12
```
```>>> xr.where(y.lat < 1, y, -1)
<xarray.DataArray (lat: 3, lon: 3)>
array([[ 0. ,  0.1,  0.2],
[-1. , -1. , -1. ],
[-1. , -1. , -1. ]])
Coordinates:
* lat      (lat) int64 0 1 2
* lon      (lon) int64 10 11 12
```
```>>> cond = xr.DataArray([True, False], dims=["x"])
>>> x = xr.DataArray([1, 2], dims=["y"])
>>> xr.where(cond, x, 0)
<xarray.DataArray (x: 2, y: 2)>
array([[1, 2],
[0, 0]])
Dimensions without coordinates: x, y
```

`numpy.where`