[英]xarray - apply a function to the time dimension of a DataArray and add the result as a variable
[英]add dimension to an xarray DataArray
我需要向DataArray
添加一个维度,填充跨新维度的值。 这是原始数组。
a_size = 10
a_coords = np.linspace(0, 1, a_size)
b_size = 5
b_coords = np.linspace(0, 1, b_size)
# original 1-dimensional array
x = xr.DataArray(
np.random.random(a_size),
coords=[('a', a coords)])
我想我可以用新维度创建一个空的 DataArray 并将现有数据复制进去。
y = xr.DataArray(
np.empty((b_size, a_size),
coords=([('b', b_coords), ('a', a_coords)])
y[:] = x
一个更好的主意可能是使用concat
。 我花了一段时间才弄清楚如何为 concat 维度指定暗淡和坐标,但这些选项似乎都不是很好。 有什么我遗漏的东西可以使这个版本更干净吗?
# specify the dimension name, then set the coordinates
y = xr.concat([x for _ in b_coords], 'b')
y['b'] = b_coords
# specify the coordinates, then rename the dimension
y = xr.concat([x for _ in b_coords], b_coords)
y.rename({'concat_dim': 'b'})
# use a DataArray as the concat dimension
y = xr.concat(
[x for _ in b_coords],
xr.DataArray(b_coords, name='b', dims=['b']))
尽管如此,有没有比上述两个选项中的任何一个更好的方法来做到这一点?
您已经对当前选项进行了非常彻底的分析,实际上这些选项都不是很干净。
这肯定是为 xarray 编写的有用功能,但还没有人开始实现它。 也许你有兴趣帮忙?
有关一些 API 建议,请参阅此 GitHub 问题: https : //github.com/pydata/xarray/issues/170
由于数学应用于新维度的方式,我喜欢乘以添加新维度。
identityb = xr.DataArray(np.ones_like(b_coords), coords=[('b', b_coords)])
y = x * identityb
如果DA
是长度为DimLen
数据数组,则现在可以使用expand_dims
:
DA.expand_dims({'NewDim':DimLen})
参考问题的语法:
y = x.expand_dims({"b": b_coords})
使用.assign_coords
方法即可。 但是,您不能将坐标分配给不存在的维度,作为单行的方法是:
y = x.expand_dims({b_coords.name: b_size}).assign_coords({b_coords.name: b_coords})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.