Add dimension to xarray DataArray

I need to add the dimension to DataArrayby filling in the values ​​in the new dimension. Here is 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 think I could create an empty DataArray with a new dimension and copy the existing data.

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

A better idea might be to use concat. It took me a while to figure out how to specify both dull and consonants for the concat measurement, and none of these options seem big. Is there something I'm missing that can make 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']))

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

+7
source share
3 answers

DA - DimLen, :

DA.expand_dim({'NewDim':DimLen})
+1

, , , .

, , xarray, . , ?

. GitHub API: https://github.com/pydata/xarray/issues/170

+4

Due to the way math is applied to new dimensions, I like to multiply to add new dimensions.

identityb = xr.DataArray(np.ones_like(b_coords), coords=[('b', b_coords)])
y = x * identityb
+4
source

Source: https://habr.com/ru/post/1655399/


All Articles