简体   繁体   English

为 xarray DataArray 添加维度

[英]add dimension to an xarray DataArray

I need to add a dimension to a DataArray , filling the values across the new dimension.我需要向DataArray添加一个维度,填充跨新维度的值。 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)])

I guess I could create an empty DataArray with the new dimension and copy the existing data in.我想我可以用新维度创建一个空的 DataArray 并将现有数据复制进去。

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

A better idea might be to be to use concat .一个更好的主意可能是使用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.我花了一段时间才弄清楚如何为 concat 维度指定暗淡和坐标,但这些选项似乎都不是很好。 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?尽管如此,有没有比上述两个选项中的任何一个更好的方法来做到这一点?

You've done a pretty thorough analysis of the current options, and indeed none of these are very clean.您已经对当前选项进行了非常彻底的分析,实际上这些选项都不是很干净。

This would certainly be useful functionality to write for xarray, but nobody has gotten around to implementing it yet.这肯定是为 xarray 编写的有用功能,但还没有人开始实现它。 Maybe you would be interested in helping out?也许你有兴趣帮忙?

See this GitHub issue for some API proposals: https://github.com/pydata/xarray/issues/170有关一些 API 建议,请参阅此 GitHub 问题: https : //github.com/pydata/xarray/issues/170

Because of the way that math is applied over new dimensions I like to multiply in order to add new dimensions.由于数学应用于新维度的方式,我喜欢乘以添加新维度。

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})

Using .assign_coords method will do it.使用.assign_coords方法即可。 However you can't assign coordinates to a non-existant dimension, the way to do as a one liner is:但是,您不能将坐标分配给不存在的维度,作为单行的方法是:

y = x.expand_dims({b_coords.name: b_size}).assign_coords({b_coords.name: b_coords})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM