Combining a set of 2D variables into a 3D DataArray

I have a simple situation, a dataset made up of 50 data arrays all with two dimensions that are the same for all dataArrays (time, satellite) and both dimensions have the same values in each data array. Each of these data arrays has a name which is a string, i.e ‘C2C’. I would like to combine these into a 3D dataset with the outside dimension being the variable name from the original dataset. I have read merge and concat but can not get either to work…

2 Likes

You are on the right track. You want to use Xarray’s concat feature. Here is a simple example.

import xarray as xr
foo = xr.DataArray([1, 2], dims='time', name='foo')
bar = xr.DataArray([3, 4], dims='time', name='bar')
# the trick: create a new DataArray to represent the new dimension
name_da = xr.DataArray([da.name for da in (foo, bar)], name='varname')
combined = xr.concat([foo, bar], dim=name_da)
1 Like

Ryan,

Hmmm - there is a trick! I will give this a try soon.

Thanks,
Ted

The trick is not a dealbreaker. You could also just do xr.concat(..., dim="varname") but then you not have a labeled coordiante for the varname dimension.

1 Like

Ryan,

Thanks again for the pointer. I ended up getting the desired result with
station = xr.concat(obs.values(),dim=list(obs.data_vars)).
rename({‘concat_dim’:‘observation’}).
rename(‘observations’)
where obs is the original dataSet and station is the new dataset…

Ted

1 Like