Stack Xarray Dataarray

Stack Xarray Dataarray

I have N 1D xr.DataArray's with an 1 array coordinate b and 1 scalar coordinate a. I want to combine them to a 2D DataArray with array coordinates b, a. How to do this? I have tried:

x1 = xr.DataArray(np.arange(0,3)[...,np.newaxis], coords=[('b', np.arange(3,6)),('a', [10])]).squeeze()
x2 = xr.DataArray(np.arange(0,3)[...,np.newaxis], coords=[('b', np.arange(3,6)),('a', [11])]).squeeze()

xcombined = xr.concat([x1, x2])
xcombined

Results in :

<xarray.DataArray (concat_dims: 2, b: 3)>
array([[0, 1, 2],
       [0, 1, 2]])
Coordinates:
  * b        (b) int64 3 4 5
    a        (concat_dims) int64 10 11
Dimensions without coordinates: concat_dims

Now I like to select a particularly 'a':

xcombined.sel(a=10)

However, this raises:

ValueError: dimensions or multi-index levels ['a'] do not exist

1 Answer

If you supply dim to concat, this works:

xcombined = xr.concat([x1, x2], dim='a')

And then:

xcombined.sel(a=10)

<xarray.DataArray (b: 3)>
array([0, 1, 2])
Coordinates:
  * b        (b) int64 3 4 5
    a        int64 10
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.