向xarray DataArray添加维度 [英] add dimension to an xarray DataArray

查看:524
本文介绍了向xarray DataArray添加维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向DataArray添加一个维度,以填充新维度中的值.这是原始数组.

I need to add a dimension to a DataArray, filling the values across the new dimension. Here's the original array.

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并复制其中的现有数据.

I guess I could create an empty DataArray with the new dimension and copy the existing data in.

y = xr.DataArray(
    np.empty((b_size, a_size),
    coords=([('b', b_coords), ('a', a_coords)])
y[:] = x

一个更好的主意可能是使用concat.我花了一段时间才弄清楚如何为concat尺寸指定调暗和坐标,这些选项似乎都不是很好.我缺少什么可以使此版本更清洁的东西吗?

A better idea might be to be to use concat. It took me a while to figure out how to specify both the dims and the coords for the concat dimension, and none of these options seem great. Is there something I'm missing that can makes this version cleaner?

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

还是,有没有比上述两个选项更好的方法了?

Still, is there a better way to do this than either of the two above options?

推荐答案

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

If DA is your data array with length DimLen, you can now use expand_dims:

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

这篇关于向xarray DataArray添加维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆