10

我需要向 a 添加一个维度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']))

不过,还有比上述两个选项更好的方法吗?

4

5 回答 5

5

如果DA您的数据数组长度为DimLen,您现在可以使用expand_dims

DA.expand_dims({'NewDim':DimLen})
于 2019-10-02T10:14:56.290 回答
4

您已经对当前选项进行了非常彻底的分析,实际上这些选项都不是很干净。

这肯定是为 xarray 编写的有用功能,但还没有人开始实施它。也许你有兴趣帮忙?

有关一些 API 提案,请参阅此 GitHub 问题:https ://github.com/pydata/xarray/issues/170

于 2016-09-21T22:03:56.283 回答
4

由于数学应用于新维度的方式,我喜欢相乘以添加新维度。

identityb = xr.DataArray(np.ones_like(b_coords), coords=[('b', b_coords)])
y = x * identityb
于 2017-07-12T17:58:37.973 回答
1

参考问题的语法:

y = x.expand_dims({"b": b_coords})
于 2019-12-16T02:54:32.180 回答
1

使用.assign_coords方法会做到这一点。但是,您不能将坐标分配给不存在的维度,作为单行的方法是:

y = x.expand_dims({b_coords.name: b_size}).assign_coords({b_coords.name: b_coords})
于 2020-05-05T18:26:51.337 回答