Stack xarray DataArray
Publish date: 2024-04-27
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 2ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobG1rZGt%2Bc4WOrKuam5tixaK%2B0ZqwZpyRqa6ivtGasA%3D%3D