为 xarray DataArray 添加维度

14

我需要将一个 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。我花了一些时间才弄清楚如何为连接维度同时指定维度和坐标,而且这些选项都不太好。我是否错过了什么可以让这个版本更简洁?

# 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个回答

13
如果 DA 是长度为 DimLen 的数据数组,则现在可以使用 expand_dims
DA.expand_dims({'NewDim':DimLen})

4
使用.assign_coords方法可以实现这一功能。但是您不能为不存在的维度分配坐标,一行代码的方法如下:
y = x.expand_dims({b_coords.name: b_size}).assign_coords({b_coords.name: b_coords})

4
因为数学是通过新的维度来应用的,所以我喜欢乘法来添加新的维度。
identityb = xr.DataArray(np.ones_like(b_coords), coords=[('b', b_coords)])
y = x * identityb

1
快速解决方案,尽管会导致丢失x中可用的属性。 - susopeiz

1
关于问题的语法,请参考以下内容:
y = x.expand_dims({"b": b_coords})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接