简体   繁体   中英

add dimension to an xarray 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)])

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

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?

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. Maybe you would be interested in helping out?

See this GitHub issue for some API proposals: 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. 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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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