xarray:如何将数组添加到特定维度?

时间:2018-03-14 16:43:35

标签: python pandas data-structures python-xarray xarray

一个简单的例子如下:

arr = xr.DataArray(np.random.rand(2,3,4), coords={'x': ['a', 'b'], 'y': ['c','d', 'e'], 'z': ['f', 'g', 'h', 'i']}, dims=('x', 'y', 'z'))
to_add = np.random.rand(3,4)

如何将to_add添加到x中与arr标签相似的a_plus

所以结果如下:

<xarray.DataArray (x: 3, y: 3, z: 4)>
array([[[0.753333, 0.585982, 0.271593, 0.017763],
        [0.858164, 0.628703, 0.951855, 0.097232],
        [0.372766, 0.006932, 0.848118, 0.06778 ]],

       [[0.935869, 0.517625, 0.841972, 0.116477],
        [0.161093, 0.449632, 0.640333, 0.578949],
        [0.613066, 0.315713, 0.227409, 0.853698]],

       [[0.405509, 0.194987, 0.662878, 0.105522],
        [0.565623, 0.436369, 0.153299, 0.72756 ],
        [0.589336, 0.957754, 0.645316, 0.319808]]])
Coordinates:
  * y        (y) |S1 'c' 'd' 'e'
  * x        (x) |S6 'a' 'b' 'a_plus'
  * z        (z) |S1 'f' 'g' 'h' 'i'

1 个答案:

答案 0 :(得分:1)

如何使用xr.concat

In [2]: to_add = xr.DataArray(to_add[np.newaxis, ...], dims=('x', 'y', 'z'), 
   ...:                       coords={'x': ['a_plus']})
   ...: 
   ...: xr.concat([arr, to_add], dim='x')
   ...: 
Out[2]: 
<xarray.DataArray (x: 3, y: 3, z: 4)>
array([[[0.77673 , 0.824249, 0.322716, 0.112895],
        [0.370895, 0.822571, 0.313705, 0.791842],
        [0.050617, 0.748153, 0.468028, 0.45783 ]],

       [[0.533804, 0.3056  , 0.045392, 0.741007],
        [0.155017, 0.074398, 0.664608, 0.778044],
        [0.202733, 0.265853, 0.326244, 0.840031]],

       [[0.466699, 0.118699, 0.841625, 0.822482],
        [0.755435, 0.334517, 0.389928, 0.885802],
        [0.985752, 0.992393, 0.977829, 0.992257]]])
Coordinates:
  * y        (y) object 'c' 'd' 'e'
  * z        (z) object 'f' 'g' 'h' 'i'
  * x        (x) object 'a' 'b' 'a_plus'