gpt4 book ai didi

python - 向 xarray DataArray 添加维度

转载 作者:太空狗 更新时间:2023-10-29 21:39:03 24 4
gpt4 key购买 nike

我需要向 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 维度指定 dims 和 coords,这些选项似乎都不是很好。有没有我遗漏的东西可以使这个版本更干净?

# 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']))

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

最佳答案

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

DA.expand_dims({'NewDim':DimLen})

关于python - 向 xarray DataArray 添加维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39626402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com