如何用 Python 中的常量(比如 5)替换 xarray 的所有值?

How to replace all values of an xarray with a constant (say 5) in Python?

我知道如何使用 .where 根据 等条件替换值,但我想知道如何用数字替换 xarray 中的所有值。

提前致谢

根据文档 here,您只需:

a = xr.DataArray(np.arange(16).reshape(4, 4), dims=['x', 'y'])

b = a.where(a > 5, other=5)
b = b.where(b < 5, other=5)

正如 r-beer 所建议的那样,直接的方法是:

a = a.where(a == 5, other=5)

使用以下代码可能更直接:

a = xr.DataArray(np.arange(16).reshape(4, 4), dims=['x', 'y'])

c = a.where(a == 5, other=5)