如何使用 sel 更改 xarray.DataArray 中的单个条目?
How to change individual entries in xarray.DataArray with sel?
我在 xarray.DataArray 中有我想要操作的数据,但是,它无法更改 DataArray 中的单个条目。
示例:
import numpy as np
import xarray as xr
data = np.random.rand(2,2)
times = [1998,1999]
locations = ['It','Be']
A = xr.DataArray(data, coords = [times, locations], dims = [time, space])
这给了我一个 DataArray。现在我想将 (1998,'It') 的条目手动设置为 5,但以下不起作用:
A.sel(time = 1998, space = 'It').values = 5
这都行不通:
A.sel(time = 1998, space = 'It').values = array(5)
数据保持原样。然而,奇怪的是下面的效果很好:
A.sel(time = 1998).values[0] = 5
你能解释一下这背后的逻辑吗?
Xarray 的赋值不允许您使用 sel
或 isel
为数组赋值。这在文档 here 中有描述。对于您的应用程序,您可能希望使用 .loc
属性:
A.loc[dict(time=1998, space='It')] = 5
也可以使用DataArray.where
来替换值。
我在 xarray.DataArray 中有我想要操作的数据,但是,它无法更改 DataArray 中的单个条目。
示例:
import numpy as np
import xarray as xr
data = np.random.rand(2,2)
times = [1998,1999]
locations = ['It','Be']
A = xr.DataArray(data, coords = [times, locations], dims = [time, space])
这给了我一个 DataArray。现在我想将 (1998,'It') 的条目手动设置为 5,但以下不起作用:
A.sel(time = 1998, space = 'It').values = 5
这都行不通:
A.sel(time = 1998, space = 'It').values = array(5)
数据保持原样。然而,奇怪的是下面的效果很好:
A.sel(time = 1998).values[0] = 5
你能解释一下这背后的逻辑吗?
Xarray 的赋值不允许您使用 sel
或 isel
为数组赋值。这在文档 here 中有描述。对于您的应用程序,您可能希望使用 .loc
属性:
A.loc[dict(time=1998, space='It')] = 5
也可以使用DataArray.where
来替换值。