Reputation: 123
Let's assume we do have multiple values with assigned coordinates:
a = []
a.append(xr.DataArray([[5.]], dims=('x', 'y'), coords=dict(x=[1.],y=[2.])))
a.append(xr.DataArray([[1.]], dims=('x', 'y'), coords=dict(x=[2.],y=[2.])))
a.append(xr.DataArray([[2.]], dims=('x', 'y'), coords=dict(x=[1.],y=[1.])))
I now want to combine all DataArrays in a
into one single new DataArray with combined coordinates. I.e. the three values 5, 1, 2 with the coordinates assigned. Not provided (missing) values could be filled with anything (0, None, …).
If I would do this operation along one axis, I'd use concatenate
, but what should I do in the case of multiple dimensions? Thanks a lot in advance for your kind help!
Upvotes: 2
Views: 4428
Reputation: 8763
You can use combine_by_coords
. It works with Datasets, so you'll need to either use Datasets or set the name
of the DataArrays:
a = []
a.append(xr.DataArray([[5.]], dims=('x', 'y'), coords=dict(x=[1.],y=[2.]), name="var"))
a.append(xr.DataArray([[1.]], dims=('x', 'y'), coords=dict(x=[2.],y=[2.]), name="var"))
a.append(xr.DataArray([[2.]], dims=('x', 'y'), coords=dict(x=[1.],y=[1.]), name="var"))
xr.combine_by_coords(a)
# Output
# <xarray.Dataset>
# Dimensions: (x: 2, y: 2)
# Coordinates:
# * x (x) float64 1.0 2.0
# * y (y) float64 1.0 2.0
# Data variables:
# var (x, y) float64 2.0 5.0 nan 1.0
To avoid unexpected results and warnings during the conversion from DataArray to Dataset, I would recommend to explicitly convert the objects first to Dataset, then use combine_by_coords
and eventually convert back to DataArray if desired.
Upvotes: 3