如何将两个具有相同维度和坐标的 2D xarray.DataArray 合并为一个 3D xarray.DataArray?

问题描述 投票:0回答:1

我有这两个数组(

chars
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
)

我想将它们组合成

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'])
    ]
)

我试图了解 xarray 的 combing data 选项,但无法识别正确的方法,更不用说参数值了。

如何组合数组?

python-xarray
1个回答
0
投票

我希望这有帮助。我将执行以下操作。 :

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)

给出输出:

<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'
© www.soinside.com 2019 - 2024. All rights reserved.