Search code examples
pythonconcatenationpython-xarray

How to use xarray to concatenate along a new dimension while preserving the other dimensions


I have a dictionary of several 3d arrays which I would like to concatenate into a single 4d array.

<xarray.DataArray 'q' (time: 12, latitude: 129, longitude: 121)>

When I concatenate the arrays I get:

stack=xr.concat([reshape_shum[i] for i in np.arange(1980,2000)], 'years')
print(stack)
<xarray.DataArray 'q' (years: 20, time: 240, latitude: 129, longitude: 121)>

Is it possible to preserve the time dimension so as to get the following?

<xarray.DataArray 'q' (years: 20, time: 12, latitude: 129, longitude: 121)>

I know I can get this shape with:

stack=np.stack(reshape_shum[i] for i in np.arange(1980,2020))
stack.shape
(20, 12, 129, 121)

Solution

  • Thanks to the comments, I was able to solve my issue. My time dimension was datetime64 and I changed this to integers as follows:

    for i in np.arange(1980,2000):
    reshape_shum[i].coords['time']=np.arange(1,13)
    stack=xr.concat([reshape_shum[i] for i in np.arange(1980,2000)],  pd.Index(np.arange(1980,2000), name='years'))
    print(stack)
    <xarray.DataArray 'q' (years: 20, time: 12, latitude: 129, longitude: 121)>