Search code examples
python-xarray

How to combine two 2D xarray.DataArrays with equal dimensions and coords into one 3D xarray.DataArray?


I have these two arrays (chars and numbers):

chars = xarray.DataArray(
    data=[['A', 'B', 'C'],
          ['D', 'E', 'F'],
          ['G', 'H', 'I']],
    coords=[
        ('row', [1, 2, 3]),
        ('col', [10, 20, 30])
    ]
)

numbers = xarray.DataArray(
    data=[[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]],
    coords=chars.coords
)

I want to combine them into

desired = xarray.DataArray(
    data=[[['A', 1], ['B', 2], ['C', 3]],
          [['D', 4], ['E', 5], ['F', 6]],
          [['G', 7], ['H', 8], ['I', 9]]],
    coords=[
        ('row', [1, 2, 3]),
        ('col', [10, 20, 30]),
        ('type', ['my_char', 'my_int'])
    ]
)

I tried to wrap my head around xarray's combing data options, but wasn't able to identify the right method, let alone parameter values.

How can I combine the arrays?


Solution

  • I hope this helps. I would perform the following. :

    import xarray as xr
    combine = xr.concat([chars, numbers.rename('my_int')], dim='type')
    
    # swaps dimension to match the desired order and renames 'type' dimensions
    combined = combined.transpose('row','col','type')
    combined = combined.assign_coords( type = ['my_char',  'my_int'])
    
    # displays result
    print(combined)
    

    Which gives the output:

    <xarray.DataArray (row: 3, col: 3, type: 2)>
    array([[['A', 1],
            ['B', 2],
            ['C', 3]],
    
           [['D', 4],
            ['E', 5],
            ['F', 6]],
    
           [['G', 7],
            ['H', 8],
            ['I', 9]]], dtype=object)
    Coordinates:
      * row      (row) int32 1 2 3
      * col      (col) int32 10 20 30
      * type     (type) <U7 'my_char' 'my_int'